5. Concurrent

1. Origin

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

When you meet these above red, indicating that you encounter concurrency problem of ef.

When the two connections operating simultaneously made to the database of conflict, such as deleting a connection, a connection changes. When the deletion occurs before the change, there will be the exception.

There is another situation is to create a new object in the datacontext, but his status as modified from the editor added

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

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

 

2. Measures

A common solution to the problem, there are two concurrent,

First, when this occurs when abnormal, the state entity on the database backfill

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

Second, the local entity added to a state modified from

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

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

 

Guess you like

Origin www.cnblogs.com/nocanstillbb/p/11494708.html