5.并发

1.缘起

Exception: Store update, insert, or delete statement affected an unexpected number of rows (0)

当你遇到上面这些红字,说明你遇到了ef的并发问题.

当两个连接同时向数据库做了冲突的操作,比如一个连接删除,一个连接更改.当删除发生在更改之前,就会出现这个异常.

还有另一个情况是在datacontext中创建了一个新的对象,但是将他的状态从added编辑成modified

using (var context = new EntityContext())
{
    var customer = new Customer();
    // ...code...

    context.Entry(customer).State = EntityState.Modified;
    context.SaveChanges();
}

2.对策

解决并发问题的常见方法有两种,

一是当出现这个异常时,把数据库上的状态回填实体

using (var context = new EntityContext())
{
    // ...code...
    try
    {
        context.SaveChanges();
    }
    catch (DbUpdateConcurrencyException ex)
    {
        var value = ex.Entries.Single();
        value.OriginalValues.SetValues(value.GetDatabaseValues());
        context.SaveChanges();
    }
}

二是把本地的实体状态从modified改为added

using (var context = new CustomerContext())
{
    var customer = new Customer();
    // ...code...

    context.Entry(customer).State = EntityState.Added;
    context.SaveChanges();
}

猜你喜欢

转载自www.cnblogs.com/nocanstillbb/p/11494708.html