views:

322

answers:

2

I'm using Entity Framework with an AS.NET MVC application. I need to allow the user to create new records and modify existing ones. I am able to fetch existing records no problem, but when I pass back in the edited entity and try to save it it creates a new one and saves it and leaves the original unmodified.

I am getting the object from EF using the primary key (e.g. ID number for an employee record). I successfully retrieve it, and set the MergeOption like so:

Context.Sector.MergeOption = MergeOption.NoTracking;

I am able to trace that the object has the correct data (using the key of the original record) all the way down to the point where I call:

Context.SaveChanges();

However, after that, the new record is created instead of modifying the existing one.

Is there something obvious I am missing here? I would have thought that retrieving the object and changing some of its values (not the ID) and saving it would just work, but obviously not.

Thanks,

Chris

+3  A: 

"NoTracking means that the ObjectStateManager is bypassed and therefore every access to the Entity Objects results in a fetch from the database and the creation of new objects."

-- http://blog.dynatrace.com/2009/03/11/adonet-entity-framework-unexpected-behaviour-with-mergeoptions/

I don't think NoTracking is what you want.

DaRKoN_
I really wonder why he would go and set the mergeoption to NoTracking. He hasn't explained the reason. It sounds extremely plausible that this is where he makes his mistake. If object-services is no-longer able to track changes on an entity, then the entity will be assumed to be new.
CodeMonkey
A: 

From your comment: "distributed across various tiers and some proprietary libraries"

Are you new()ing up a ObjectContext, closing it or losing the reference to it, and then trying to save your object to a new() or different ObjectContext?

If so your losing all of your change tracking information. If this is the case then you want to call the Attach() method to reattach the entity to the context, ApplyPropertyChanges() and then finally SaveChanges().

Julie Lerman has a pretty good blog post that outlines all the different change tracking options and techniques that are available. You should also check out this MSDN article on the same subject.

jfar