DbUpdateException上的SaveChanges如果孩子外键已经存在 - 在实体框架$ C C首先$实体、框架、存在、孩子

2023-09-05 04:37:23 作者:互不相扰 互不相欠

[使用$ C C第一的DbContext $实体框架5.0 RC 的]

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; }
}

第一关 - SaveChanges的以空数据库工程

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:更新条目时发生错误

我需要能够保存这些父类到数据库中,因为它们是独一无二的,即使他们有时包含已存储的导航性能 - ?我怎么能救母从此子主键冲突

推荐答案

在第二遍,你将需要检索现有的心眼的DbContext 。我猜,你能做到这一点是这样的:

In the second pass you will need to retrieve the existing Simpleton from the DbContext. I'm guessing that you could do that like this:

`simpleton = Repositor.Simpletons.First(s => s.Id == "Simpleton1");`

目前,您要创建一个全新的,它的实体框架试图插入这样,因此键冲突。

Currently, you're creating a brand new one, which the Entity Framework tries to insert as such, hence the key violation.