多个添加的实体可能在实体框架中具有相同的主键 [英] Multiple added entities may have the same primary key in Entity Framework

查看:383
本文介绍了多个添加的实体可能在实体框架中具有相同的主键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



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



现在,如果没有添加到系统即将添加,他也指系统中的另一个员工,该行应该完全添加。



ActualEmployee 保存未调用,然后 ReferEmployee.Employee = ActualEmployee



我明白问题是员工实际并且将Employee ID设置为0,但是如何解决这个问题。

解决方案

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



创建两个新员工 - 一个引用另一个
Employee john = new Employee {EmployeeID = -1,EmpName =John};


员工peter = new Employee {EmployeeID = -2,EmpName =Peter,ReferEmployeeID = -1};

//将它们添加到EF模型
ctx.AddToEmployees(john);
ctx.AddToEmployees(peter);

//保存更改
ctx.SaveChanges();

所以基本上,用dummy定义你的新员工 EmployeeID 值,并通过其虚拟ID建立链接( Peter 引用 John



将其保存到SQL Server中时,实体框架将处理实现 EmployeeID 值(SQL Server在插入行时会出错),EF将维护两名员工之间的链接。


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 referring a new employee in the system. So Employee is a self-referencing table.

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

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.

解决方案

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.

这篇关于多个添加的实体可能在实体框架中具有相同的主键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆