C# 代码优先EF模型问题
遇到一个问题,查看C# 代码优先EF模型问题,c#,entity-framework,ef-code-first,code-first,C#,Entity Framework,Ef Code First,Code First,遇到一个问题,查看Group.Members.Count()将返回0 public class Employee { public Guid Id { get; set; } public String Name { get; set; } public Guid? PrimaryGroupId { get; set; } [ForeignKey("PrimaryGroupId")] public virtual Group PrimaryGroup
Group.Members.Count()
将返回0
public class Employee
{
public Guid Id { get; set; }
public String Name { get; set; }
public Guid? PrimaryGroupId { get; set; }
[ForeignKey("PrimaryGroupId")]
public virtual Group PrimaryGroup { get; set; }
public virtual ICollection<Address> Addresses { get; set; }
public virtual ICollection<PhoneNumber> PhoneNumbers { get; set; }
public virtual ICollection<Activity> Activities { get; set; }
}
public class Group
{
public Group()
{
Id = Guid.NewGuid();
}
public Guid Id { get; set; }
public String Name { get; set; }
public Guid? GroupOwnerId{ get; set; }
[ForeignKey("GroupOwnerId")]
public virtual Employee GroupOwner{ get; set; }
public virtual ICollection<Employee> Members{ get; set; }
}
疯狂的是,Employee表上存在两个PrimaryGroupId列,如果编辑员工后我将GUID从该记录复制到PrimaryGroup_Id列,则Groups视图上的计数确实会增加。感觉像是某种FK问题。EF必须在将
成员链接到PrimaryGroupId
时遇到问题,因此请明确声明反向导航属性以帮助解决此问题:[ForeignKey(“PrimaryGroupId”),InverseProperty(“Members”)]
如果我复制您的代码(不包括地址
、电话号码
和活动
属性),我确实会获得附加的Id属性,但它被称为组Id
:
CreateTable(
"dbo.Employees",
c => new
{
Id = c.Guid(nullable: false),
Name = c.String(),
PrimaryGroupId = c.Guid(),
Group_Id = c.Guid(),
})
.PrimaryKey(t => t.Id)
.ForeignKey( "dbo.Groups", t => t.Group_Id)
.ForeignKey( "dbo.Groups", t => t.PrimaryGroupId)
.Index(t => t.PrimaryGroupId)
.Index(t => t.Group_Id);
如果我如上所述添加InverseProperty(“成员”)
,我会得到:
CreateTable(
"dbo.Employees",
c => new
{
Id = c.Guid(nullable: false),
Name = c.String(),
PrimaryGroupId = c.Guid(),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Groups", t => t.PrimaryGroupId)
.Index(t => t.PrimaryGroupId);
你把桌子包括进去了吗?您是否启用了延迟加载?包含在select上。由于没有延迟加载,我的代码将在调用Groups.Employees.Count()时抛出异常,其中Employees将为NULL。问题似乎是PrimaryGroupId得到了2列而不是1列。是的,这是同一个问题。添加注释可以解决您的问题否?
CreateTable(
"dbo.Employees",
c => new
{
Id = c.Guid(nullable: false),
Name = c.String(),
PrimaryGroupId = c.Guid(),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Groups", t => t.PrimaryGroupId)
.Index(t => t.PrimaryGroupId);