【问题标题】:Multiple added entities may have the same primary key in Entity Framework多个添加的实体在实体框架中可能具有相同的主键
【发布时间】:2012-01-21 18:26:11
【问题描述】:

我正在一个使用 EF 4.0 的项目中工作。

Employee 表有一个列 ReferEmployeeID,其中包含在系统中推荐新员工的员工的员工 ID。所以Employee 是一个自引用表。

现在如果一个未添加到系统的员工即将添加,并且他还引用了系统中的另一个员工,则应该将该行全部添加。

ActualEmployeesave 尚未调用然后ReferEmployee.Employee = ActualEmployee

我知道问题是员工实际和推荐的员工 ID 都设置为 0,但是如何解决这个问题。

【问题讨论】:

    标签: c# entity-framework


    【解决方案1】:

    假设你的数据库表中的EmployeeID被定义为INT IDENTITY,那么你可以这样做:

    // create two new employees - one refers to the other
    Employee john = new Employee { EmployeeID = -1, EmpName = "John" };
    Employee peter = new Employee { EmployeeID = -2, EmpName = "Peter", ReferEmployeeID = -1 };
    
    // add them to the EF model
    ctx.AddToEmployees(john);
    ctx.AddToEmployees(peter);
    
    // save changes
    ctx.SaveChanges();
    

    因此,基本上,使用“虚拟”EmployeeID 值定义您的新员工并建立链接(Peter 在此处引用 John,通过其“虚拟”ID)。

    将其保存到 SQL Server 时,实体框架将处理获取 real EmployeeID 值(SQL Server 在插入行时发出)的过程,并且 EF 将维护该链接两个员工。

    【讨论】:

    • 我一直在寻找这个答案大约两个小时。我从来不知道 EF 是这样工作的(使用虚拟身份)。这在任何地方都有记录或讨论吗?谢谢!
    • @Mike:不确定 - 我在某处找到它,阅读 Julie Lerman 和 EF 团队的书籍、博客和介绍视频
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-27
    • 2018-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-15
    相关资源
    最近更新 更多