我对 Entity Framework 比较陌生。最近我遇到了这种奇怪的行为(在我看来),这让我很困惑。
如果我将其状态设置为已删除,为什么被跟踪的实体会从 dbContext 中删除?
例如:
var customers = db.Customers
.Where(customer => customer.FirstName.Contains("John"))
.Take(10)
.ToList();
//Let's iterate through the customers -list
//and remove the 5th customer
int i = 1;
foreach(var customer in customers)
{
if(i == 5)
{
//An exception will be thrown
db.Entry(customer).State = EntityState.Deleted;
}
i++;
}
当第 5 个客户的状态从 Unchanged
更改为 Deleted
时,整个对象将从上下文中甚至从 customers
中销毁 -列表。更糟糕的是:这也会引发异常,因为此操作会更改我们正在迭代的列表!
谁能向我解释为什么在通过调用 db.SaveChanges()
将更改保存到数据库之前会发生这种情况?
最佳答案
Why does tracked entity gets removed from the dbContext if I set it's state to Deleted?
为了防止像这样非常奇怪的事情......
foreach(var customer in customers)
{
db.Entry(customer).State = EntityState.Deleted;
}
foreach(var customer in customers)
{
Console.WriteLine("I'm a deleted customer that still exists");
}
由此产生的后果将迫使我们编写这样的代码。
foreach(var customer in customers)
{
//Extra code to make sure nothing deleted is in here
if(db.Entry(customer).State != EntityState.Deleted)
{
//Do work
}
}
请注意,该对象仍然存在于 ObjectStateManager 中,但与对象图的任何正常交互都不会产生任何已删除的对象。你仍然可以看到它像这样存在......
var customer = customers.First();
db.Entry(customer).State = EntityState.Deleted;
Console.WriteLine(db.Entry(customer).State.ToString()); //Deleted
关于c# - 将实体的状态设置为已删除会将实体从 dbContext 中删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28156638/