清除EntityCollection,然后似乎无法在同一事务中添加到它 [英] Clear an EntityCollection and then Add to it within the same transaction doesn't seem possible
问题描述
我有2个实体:部门和雇员。 1个部门可以有很多员工。我想清除现有部门中的所有雇员,并将新雇员添加到该部门中,然后保存更改。它必须在单个事务中。
I have 2 entities a Department and an Employee. 1 Department can have many Employees. I would like to clear all the Employees from an existing Department, and also add a new Employee to that same department and then save the changes. It must be within a single transaction.
但是,当我尝试执行下面的代码时,数据库上出现键冲突错误。看来这显然不是要删除DepartmentEmployee表中的项目,然后再插入新的Employee。
However when I try execute the code below I get a key violation error on the database. It seems that the clear is not deleting the items in the DepartmentEmployee table, and then inserting the new Employee.
Employee newEmployee = GetNewEmployee();
department.Employees.Clear();
department.Employees.Add(newEmployee);
EntityContext.ApplyPropertyChanges("SetName", department);
EntityContext.SaveChanges();
任何对此的帮助将不胜感激。谢谢。
Any help with this would be greatly appreciated. Thanks.
推荐答案
我认为您无法通过一次调用 SaveChanges $来做到这一点。 c $ c>。实体框架不保证任何特定的操作顺序。因此,我认为没有任何方法可以强制DELETE在插入之前出现,而无需另外调用
SaveChanges
。
I don't think you can do this in one call to SaveChanges
. The Entity Framework does not guarantee any specific order of operations. So I don't think there is any way to force the DELETE to come before the INSERT without an additional call to SaveChanges
.
另一方面,您可能可以在一个数据库事务中完成此操作。只需在新的 TransactionScope
内完成操作即可。
On the other hand, you probably can do it in one database transaction. Just do it inside a new TransactionScope
.
尝试:
using (var t = new TransactionScope())
{
Employee newEmployee = GetNewEmployee();
department.Employees.Clear();
EntityContext.SaveChanges();
department.Employees.Add(newEmployee);
EntityContext.ApplyPropertyChanges("SetName", department);
EntityContext.SaveChanges();
t.Complete();
}
这篇关于清除EntityCollection,然后似乎无法在同一事务中添加到它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!