C# 实体框架6可选单向关系
我有两张桌子:C# 实体框架6可选单向关系,c#,entity-framework-6,C#,Entity Framework 6,我有两张桌子: Client ------------------------ Id (string) <-- PrimaryKey Name (string) Number (int) Department:* ------------------------ Id (int) <-- Primary key Name (string) ClientNumber (int?) Client
Client
------------------------
Id (string) <-- PrimaryKey
Name (string)
Number (int)
Department:*
------------------------
Id (int) <-- Primary key
Name (string)
ClientNumber (int?)
Client (Client, virtual)
.....
在Linq中使用联接很容易做到这一点,但最好是:
dbContext.Departments.Include(d => d.Client)
在包含客户端(如果有的话)的Department类上使用虚拟属性很抱歉,这是不可能的。
EF中的Valide关系在数据库中也必须有效,换句话说,依赖表必须引用主体表中的唯一标识符。否则,系统无法确保每个部门最多有一个客户 如前所述,这“还”不可能。
实体框架7将支持此功能
对于那些希望了解最新情况的人,以下是讨论/投票功能
作为一种解决方法,您能否同时添加ClientId和ClientNumber属性?在确保客户端不为空后,您可以从虚拟客户端属性访问ClientNumber:
public class Client
{
public string Id { get; set; }
public string Name { get; set; }
public int Number { get; set; }
}
public class Department
{
public int Id { get; set; }
public string Name { get; set; }
public string ClientId { get; set; }
public virtual Client Client { get; set; }
[NotMapped]
public int? ClientNumber {
get {
return Client != null ? Client.Number : null;
}
}
}
如果不使用主键列,仍然无法在实体框架中创建关系。如果要实现这种关系,必须将客户机Id列作为外键列包含在内。如果出于某种原因,你不想这样做,你可以创建一个视图来模拟这种关系。这并不完全正确。关系应该引用EF称为主键的属性。它可以是
Client.Number
,但是该属性应该定义为模型中的主键。EF 7将支持备用键。
public class Client
{
public string Id { get; set; }
public string Name { get; set; }
public int Number { get; set; }
}
public class Department
{
public int Id { get; set; }
public string Name { get; set; }
public string ClientId { get; set; }
public virtual Client Client { get; set; }
[NotMapped]
public int? ClientNumber {
get {
return Client != null ? Client.Number : null;
}
}
}