[ 将 Code First DbContext 与 Entity Framework 5.0 RC 结合使用 ]
具有 2 个导航属性/2 个外键的实体
public class Compositon
{
public string Id { get; set; }
public string SimpletonId { get; set; }
[ForeignKey("SimpletonId")]
public Simpleton Simpleton { get; set; }
public string CompanitonId { get; set; }
[ForeignKey("CompanitonId")]
public Companiton Companiton { get; set; }
}
第一遍 - 将更改保存到空数据库有效
var composition = new Compositon();
compositon.Id = "UniquePrimaryKey";
var simpleton = new Simpleton();
// This foreign key does not exist in database yet
simpleton.Id = "Simpleton1";
composition.Simpleton = simpleton;
var companiton = new Companiton();
companiton.Id = "SomeOther1";
composition.Companiton = companiton;
// Repositor references the DbContext
Repositor.Compositons.Add(composition);
Repositor.SaveChanges();
第二遍 - 现有子外键导致父级错误
var composition = new Compositon();
compositon.Id = "AnotherUniquePrimaryKey";
var simpleton = new Simpleton();
// This foreign key already exists in database
simpleton.Id = "Simpleton1";
composition.Simpleton = simpleton;
var companiton = new Companiton();
companiton.Id = "SomeOther2";
composition.Companiton = companiton;
Repositor.Compositons.Add(composition);
Repositor.SaveChanges();
DbUpdateException: An error occurred while updating the entries.
我需要能够将这些父类保存到数据库中,因为它们是唯一的,即使它们有时包含已存储的导航属性 - 如何从该子主键冲突中保存父类?
在第二遍中,您将需要检索现有的Simpleton
来自DbContext
。我猜你可以这样做:
`simpleton = Repositor.Simpletons.First(s => s.Id == "Simpleton1");`
目前,您正在创建一个全新的实体框架,实体框架尝试将其插入,因此出现了关键违规。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)