aggaton aggaton - 1 month ago 17
C# Question

Data integrity in Entity Framework

Are there any consensus as to what is considered the best method in always maintaining data integrity in Entity Framework. i.e. when adding or deleting entities, how do I make sure the loaded model is the most recent, and that nothing has changed on the db behind my back?

A rough method that seem to work for me in the majority of cases, is to reload the context between sessions, i.e. not to have a persistent model, and reload/refresh in case of an error. This seems to work in cases of low data clashes, however is very costly when lots of changes happen in different services. Is there a flag to query if the data/row on disk have changed or event to make this refresh automatic, i.e. update any subscribers of certain tables/rows?

Answer

You probably want optimistic concurrency. EF can automatically check for any change in data before committing, and throw an exception if data has changed outside your current context. See http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/handling-concurrency-with-the-entity-framework-in-an-asp-net-mvc-application