[英]Multiple added entities may have the same primary key in Entity Framework
I am working in a project using EF 4.0. 我正在使用EF 4.0进行项目。
The Employee
table has a column ReferEmployeeID
which contains the employee id of the employee that is referring a new employee in the system. Employee
表有一列ReferEmployeeID
,其中包含引用系统中新员工的员工的员工ID。 So Employee
is a self-referencing table. 所以Employee
是一个自引用表。
Now in the case of an employee who is not added to the system is about to add and he also refers another employee in the system, the row should be added altogether. 现在,如果未添加到系统的员工即将添加,并且他还引用系统中的其他员工,则应该完全添加该行。
ActualEmployee
save not called yet and then ReferEmployee.Employee = ActualEmployee
ActualEmployee
保存尚未调用,然后是ReferEmployee.Employee = ActualEmployee
I understand the issue is that both the employees actual and refer has Employee ID set to 0, but how to come around this problem. 我理解问题是员工实际和推荐都将员工ID设置为0,但是如何解决这个问题。
Assuming that the EmployeeID
in your database table is defined as INT IDENTITY
, then you could do this: 假设数据库表中的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();
So basically, define your new employees with "dummy" EmployeeID
values and establish the link ( Peter
references John
here, by means of its "dummy" ID). 所以基本上,用“虚拟” EmployeeID
值定义你的新员工并建立链接( Peter
在这里引用John
,通过其“虚拟”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. 将此保存到SQL Server时,实体框架将处理获取真实 EmployeeID
值的过程(SQL Server在插入行时将其分发),EF将维护两个员工之间的链接。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.