我对实体框架相对较新。最近我遇到了这种奇怪的行为(在我的脑海里)真的让我很困惑。
为什么跟踪实体会从dbContext中删除,如果我将其状态设置为Deleted?
例如:
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++;
}
当第五个客户的状态从Unchanged
更改为Deleted
时,整个对象将从上下文甚至customers
- 列表中销毁。更糟糕的是:这也会引发异常,因为这个动作会改变我们正在迭代的列表!
有人可以通过调用db.SaveChanges()
向我解释为什么在将更改保存到数据库之前发生了这种情况吗?
答案 0 :(得分:4)
为什么跟踪实体会从dbContext中删除,如果我将其状态设置为已删除?
为了防止这样的事情真的很奇怪......
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