小编use*_*216的帖子

将实体的状态设置为Deleted会将实体从dbContext中删除

我对实体框架比较陌生。最近,我发现这种奇怪的行为(在我看来)确实使我感到困惑。

如果将跟踪实体的状态设置为“已删除”,为什么会从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++;
}
Run Code Online (Sandbox Code Playgroud)

当第5位客户的状态从更改为时UnchangedDeleted整个对象将从上下文甚至是customers-list中销毁。更糟糕的是:这也会引发异常,因为此操作更改了我们正在迭代的列表!

有人可以通过调用将更改保存到数据库之前向我解释为什么会发生这种情况db.SaveChanges()吗?

c# state entity-framework dbcontext

4
推荐指数
1
解决办法
2752
查看次数

标签 统计

c# ×1

dbcontext ×1

entity-framework ×1

state ×1