Multiple added entities may have the same primary key in Entity Framework

前端 未结 1 877
南笙
南笙 2021-02-07 23:57

I am working in a project using EF 4.0.

The Employee table has a column ReferEmployeeID which contains the employee id of the employee that is

1条回答
  •  盖世英雄少女心
    2021-02-08 00:16

    Assuming that the EmployeeID in your database table is defined as INT IDENTITY, then you could do this:

    // 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();
    

    So basically, define your new employees with "dummy" EmployeeID values and establish the link (Peter references John here, by means of its "dummy" ID).

    When saving this into SQL Server, the Entity Framework will handle the process of getting the real EmployeeID values (which SQL Server hands out when inserting the row) and EF will maintain that link between the two employees.

    0 讨论(0)
提交回复
热议问题