Entity Framework Optimistic Concurrency Exception not occuring

前端 未结 1 1869
粉色の甜心
粉色の甜心 2020-12-06 13:20

We have an ASP.Net MVC application that uses EF4 as its data access layer and we\'re seeing unexpected behaviour with regards to OptimisitcConcurrencyExceptions not being th

相关标签:
1条回答
  • 2020-12-06 13:58

    This is a problem. Once the column is set to Computed you can't set its value in the application (you can but the value is not used).

    Edit:

    If you load entity from database it is by default tracked with the context. The context stores its original values. Original values are for example used for snapshot change tracking but they are also used as the only valid source of Computed properties. If you set Computed property in your entity the value is not used and original value is used insted. The workaround is to modify original value (before you modify anything else):

    using (var context = new TestEntities())
    {
        var entityToUpdate = context.MyEntities.Single(e => e.Id == someId);
        entityToUpdate.Timestamp = entity.Timestamp;
    
        ObjectStateEntry entry = context.ObjectStateManager.GetObjectStateEntry(entityToUpdate);
        entry.ApplyOriginalValues(entityToUpdate);
    
        // set modified properties
        context.SaveChanges();
    }
    

    Edit 2:

    Btw. once you have both actually loaded timestamp and previously retrieved timestamp you can simply compare them in your application instead of doing it in the database.

    0 讨论(0)
提交回复
热议问题