Click here to Skip to main content
15,904,877 members
Articles / All Topics

Discarding Changes to ObjectContext in Entity Framework

Rate me:
Please Sign up or sign in to vote.
4.75/5 (3 votes)
2 Sep 2011CPOL 19.4K   1  
Discarding Changes to ObjectContext in Entity Framework

Occasionally, when calling SaveChanges() on an Entity Framework ObjectContext throws an exception within a try... catch block, you may find that a subsequent call to SaveChanges only throws the same exception. How can you get round this?

Basically, the problem stems from the fact that you made changes to your ObjectContext which the database then rejected (most likely situation, but not exclusively. There may be connectivity issues etc., etc.). However, just because you caught the exception doesn't mean that your ObjectContext isn't still in an invalid state. Unless you've made several changes to your ObjectContext object before calling SaveChanges() you can simply call AcceptAllChanges() on the object context before carrying on. This basically tells the ObjectContext to let go of all the changes made to it and basically clears the slate, allowing you to make new changes to the object and subsequently save the changes.

E.g. (Heavily abbreviated code simply to demonstrate the principle. Please don't make obvious comments about its value.)

C#
ObjectContext context = new Entities();

Client newClient = Client.CreateClient
	("johndoe", "John", "Doe", ... various other properties);
//This username is already taken and will produce a
//UniqueConstraintViolationException

try{
context.AddToClients(newClient);
context.SaveChanges();
}
catch(UniqueConstraintViolationException)
{
context.AcceptAllChanges();
//Clears the changes that caused the exception
//Look up the client with the username "johndoe" and update this client's details
//with the details passed through
}
This article was originally posted at http://dotnetadventurer.blogspot.com/feeds/posts/default

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer The Test Factory
United Kingdom United Kingdom
Experienced web and software developer who has worked for some of the best and most respected software companies in the North of England as well as spending several years self employed.

Extensive knowledge of desktop and web programming languages, particularly C#, VB.NET, JavaScript, XML, CSS, Web Services, ASP.NET.

Comments and Discussions

 
-- There are no messages in this forum --