Thursday, March 17, 2016

Using the Attach method in Entity Framework

If you are working with Entity Framework, you might encounter situations where you end up working with older versions of Entity Framework that still use ObjectContext whereas newer versions of Entity Framework use DbContext instead.

In any case, if you end up working with some old code or code samples that use ObjectContext, you may end up seeing references to using the Attach method.

However, one of the problems with using the Attach method is that it will not do anything if the object state is not tracked as modified!

Therefore, even when you call SaveChanges, your changes may not be persisted to the database!

Fortunately, there is a solution to resolving this problem by setting the EntityState to Modified.

This is outlined in this article: https://msdn.microsoft.com/en-us/data/jj592676.aspx

So your code will probably end up looking like this instead:


context.Attach(existingBlog);
context.Entry(existingBlog).State = EntityState.Modified; 
context.SaveChanges();

You can read up more about Attaching and Detaching objects using ObjectContext on MSDN here: https://msdn.microsoft.com/library/bb896271(v=vs.100).aspx

No comments:

Post a Comment