Reputation: 3350
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?
Upvotes: 1
Views: 3138
Reputation: 30152
You can do some cool thing with concurrency in EF.
Specifically I have an attribute HandleConcurrencyExceptionAttribute that you can use in an MVC project to automatically hook into the DbConcurrencyException that entity framework will throw. https://github.com/adamtuliper/EF5-for-Real-Web-Applications
If you are using web forms (or win forms/wpf) you will have to check manually for it. Search the webforms project for DbConcurrencyException
So basically:
[Timestamp]
public byte[] Timestamp { get; set; }
If you want to see it in action see the end of my video at: http://channel9.msdn.com/Events/TechEd/NorthAmerica/2012/DEV215 I talk about concurrency briefly and have a quick demo.
For the second part of your question, there is the SqlCacheDependency class http://msdn.microsoft.com/en-us/library/ms178604(v=vs.100).aspx There was also an article recently in MSDN on this as well.
Upvotes: 0
Reputation: 164301
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
Upvotes: 3