【发布时间】:2018-10-26 16:49:16
【问题描述】:
我首先使用 EF6 代码,并尝试在种子方法中添加一些测试数据。我正在使用一个自引用的对象。该引用是可选的,因此顶级元素的 ParentOrgId 为空。 OrgId 是一个身份列,所以我不为其设置 ID。我第一次运行 update-database 时,对象被正确添加并且 ParentOrgId 是正确的。第二次和任何后续时间,我运行 update-database 所有 ParentOrgIds 都更改为 null。我必须从数据库中删除条目,然后它会第一次工作,然后第二次将它们更改为空。知道为什么要删除引用吗?
对象:
public class Org
{
public int OrgId { get; set; }
public int? ParentOrgId { get; set; }
public string Name { get; set; }
public int Depth { get; set; }
public virtual Org ParentOrg { get; set; }
public virtual ICollection<Org> Children { get; set; }
}
配置:
public OrgConfiguration()
{
HasKey<int>(o => o.OrgId);
HasOptional<Org>(o => o.ParentOrg)
.WithMany(o => o.Children)
.HasForeignKey(o => o.ParentOrgId);
}
在种子方法中:
Org[] seedOrgs = new Org[4];
Org o1 = new Org();
o1.Name = "TEST";
o1.Depth = 0;
seedOrgs[0] = o1;
Org o2 = new Org();
o2.Name = "TESTC1";
o2.Depth = 1;
o2.ParentOrg = o1;
seedOrgs[1] = o2;
Org o3 = new Org();
o3.Name = "TESTC11";
o3.Depth = 2;
o3.ParentOrg = o2;
seedOrgs[2] = o3;
Org o4 = new Org();
o4.Name = "TESTC2";
o4.Depth = 1;
o4.ParentOrg = o1;
seedOrgs[3] = o4;
context.Orgs.AddOrUpdate(o => o.Name, seedOrgs);
【问题讨论】:
标签: entity-framework entity-framework-6