admin

如果子外键已经存在,则SaveChanges上的DbUpdateException-在Entity Framework代码中优先

sql

[ 在实体框架5.0 RC中使用代码优先DbContext ]

具有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.

我需要能够将这些父类保存到数据库中,因为它们有时是唯一的,即使它们有时包含已存储的导航属性,又该如何保存父类呢?


阅读 192

收藏
2021-06-07

共1个答案

admin

在第二阶段中,您将需要检索现有的SimpletonDbContext。我猜你可以这样做:

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

当前,您正在创建一个全新的实体,实体框架会尝试将其插入,从而导致密钥冲突。

2021-06-07