This project is read-only.


Provide better support for working with disconnected entities


This item is to track adding better support for change tracking with graphs of disconnected entities. For more information see this discussion:

"Merge Disconnected Object Graph"

And this user voice item:

"Merge method: automatic synchronization of relationships on a disconnected entity"
Closed Dec 5, 2016 at 11:31 PM by RoMiller
EF Team Triage: We are transitioning this project to GitHub ( As part of this transition we are bulk closing a large number of issues in order that our new issue tracker will accurately reflect the work that our team is planning to complete on the EF6.x code base.

Moving forwards, our team will be fixing bugs, implementing small improvements, and accepting community contributions to the EF6.x code base. Larger feature work and innovation will happen in the EF Core code base ( Closing a feature request in the EF6.x project does not exclude us implementing the feature in EF Core. In fact, a number of popular feature requests for EF have already been implemented in EF Core (alternate keys, batching in SaveChanges, etc.).

This is a bulk message to indicate that this issue was closed and not ported to the new issue tracker. The reasons for not porting this particular issue to GitHub may include:
• It was a bug report that does not contain sufficient information for us to be able to reproduce it 
• It was a question, but sufficient time has passed that it's not clear that taking the time to answer it would provide value to the person who asked it 
• It is a feature request that we are realistically not going to implement on the EF6.x code base
Although this issue was not ported, you may still re-open it in the new issue tracker for our team to reconsider ( We will no longer be monitoring this issue tracker for comments, so please do not reply here.


RoMiller wrote Feb 14, 2013 at 11:15 PM

EF Team Triage: We agree that this would be a good scenario to enable. Taking into account where we are in the EF6 release along with the size and the impact of this feature our team is not planning to implement it in EF6. Therefore, we are moving it to the Future release to reconsider in the next release.

bojanv55 wrote Jun 11, 2013 at 10:04 AM

GraphDiff solves the problem to some extent, but it would be much better if we could have the same syntax as in NHiberate (to call on object Graph with just method .Merge() - and every relation should be derived from existing configuration or convention).

weitzhandler wrote Jul 1, 2013 at 2:31 AM

I never knew NHibernate offers that!
I should really start adopting NHibernate for my next upcoming project. I'm now facing serious issues having to update all the descendants manually. Enormous pain.

JENSC wrote Jul 4, 2013 at 11:28 AM

I can't believe that there are only 43 votes for this,
as nearly every MS based web developer should have this requirement.
At least if you create a professional, layered architecture with persistance
ignorance etc.
I would see merging as a key feature of an ORM in conjunction with the standard responsibilities
(mapping, querying/loading, state management, data manipulation, transaction handling,..).

Merging and transition between layers is a time consuming part of each software development
but should at 95% be done automatically based on conventions with just a small share of
indivual scenario specific operations.

lennart77 wrote Jul 8, 2013 at 1:58 PM

I am also kind of baffled that EF doesn't provide support for this. It is such a common problem in all but the simplest designs with the simplest data models.

We have been looking at GraphDiff but it is still young, has some bugs and the developer currently lacks time to maintain it. GraphDiff looks very promising though, so if someone had the time to aid in its development (I don't regretfully) it could very well prove an adequate solution to the problem until its included in standard EF.

weitzhandler wrote Jul 8, 2013 at 3:54 PM

I that for the future of EF, I'd like to see an implementation of GraphDiff in both styles, Fluent API (as GraphDiff is currently implemented), and via attributes (as in NHibernate). That would be just awesome.

While exploring more about NH I'm finding out that it offers more features the EF. I'll consider using it for our next upcoming projects.
EF made a great move when making it open-source, things are obviously moving faster this way.

erictosi wrote Jul 11, 2013 at 5:18 PM

Only 54 votes ?

How do you manage your entities in complex domain with bounded contexts ?

The simple case of reference data in comboBox coming from a referential context and assigned to a BusinessContext via a navigation property is not so trivial.

ForeignKeys simplify things, but if we link an object graph it's horrible !
And "sometimes" we need entire graph and prefer delegate the loading of all detached element in another context.

ie : City/Country/CountryStates/JetLag preloaded vs a CityID

A simple service can load the complete City Graph and attach It in another context, becsause locally I need business rules with JetLag.

magnusrodrigo wrote Aug 30, 2013 at 3:24 PM

I think this is an essential feature that any developer that works with N-Layer architecture needs. Only 69 votes, this is sad.

mickey_puri wrote Oct 2, 2013 at 3:19 PM

This is such a basic requirement that the failure to deal with it feels more like an omission / bug.

This "feature request" should be re-classified as a "bug-fix" and prioritized accordingly - with a point release to plug the gap.

ltctech wrote Oct 3, 2013 at 1:25 AM

The lack of proper support for disconnected graphs in EF is a big headache. I was working on a web form with a backing entity composed of five or so tables with FK relationships to other tables based on drop down selections. When I attempted to update the entity navigation properties on the way back I had tons of relationship exceptions once attached.

Eventually I gave up and wrote an extension method that copies the scalar values of a given entity and attached it to a context with a given state. Then modified all of my code first entities navigation properties to update the associated scalar when set. Then I go through each child in the entity and attach to context using this extension method. It's a very nasty hack but it works for what I am doing with it.

jperciot wrote Oct 4, 2013 at 9:08 AM

I agree with both of these people, it's a functionaly that is crucial for developers.

I can't stand it was not added since the first release of such a great framework.

Thank you for doing the best for us !

happynomad wrote Nov 18, 2013 at 5:09 AM

I think another approach is better than the one here. Instead of sending the entire modified object graph over the wire, why not instead just send the delta? You wouldn't even need generated DTO classes in that case. If you have an opinion about this either way, please let's discuss is at .

Mady007 wrote Nov 20, 2013 at 4:07 PM

I have a scenario where a complex graph is sent over to server to merge with database. First step is compare persistent graph and transient graph then
  1. Add entities from transient graph which are missing in persistent graph.
  2. Update entities from transient graph which are matching in persistent graph.
  3. Delete entities from persistent graph which are not found in transient graph.
    This is the obvious case and valid steps if the transient graph is generated from the database though it is disconnected. I do not want you to confuse with concurrency lets keep it simple.
The step 3 is not valid if the transient graph is not generated from database rather it is build from various sources and sent over to server to merge with database. In this scenario, if you analyze step 3 If an entity in a collection is not present in the transient graph which may be existing on the persistent graph will be deleted.
I found Graphdiff can address this issue with a small change. The following link may not sound good presentation of the issue but it gives you the general Idea

canotony wrote Dec 11, 2013 at 7:19 PM

Agreed, this should have way more votes.

As many before already established this is a very common scenario for anybody working in an NTier app. Currently we are "manually" building the object graph (for persistence) using the navigation properties in the POCO entities

Hopefully the low number of votes will not be a factor in giving this feature a higher priority . This will greatly enhance the capabilities of what is already a very good framework.


programad wrote Jan 16, 2014 at 10:14 AM

I wrote a very poor implementation for "merge". Any additions are welcome.
foreach (var property in typeof(T).GetProperties())
                        var subEntity = property.GetValue(entity);
                        if (subEntity != null)
                            var subEntityType = subEntity.GetType();

                            if (!subEntityType.Namespace.Equals("System") && !subEntityType.Namespace.Equals("System.Collections.Generic") && !subEntityType.IsEnum)
                                var subDbSet = db.Set(subEntityType);
                                subDbSets.Add(subEntityType, subDbSet);

                                bool isNewEntity = false;
                                var compositeKey = db.KeysFor(subEntityType);
                                object[] actualKey = new object[compositeKey.Count()];

                                for (int i = 0; i < compositeKey.Count(); i++)
                                    var primaryKeyProperty = subEntityType.GetProperty(compositeKey.ElementAt(i));
                                    var primaryKeyValue = primaryKeyProperty.GetValue(subEntity);

                                    actualKey[i] = primaryKeyValue;

                                    if (primaryKeyProperty.PropertyType == typeof(int))
                                        if ((int)primaryKeyValue == 0)
                                            isNewEntity = true;

                                if (isNewEntity)
                                    var obj = subDbSet.Find(actualKey);
                                    if (obj != null)
                                        property.SetValue(entity, obj);

Inglor wrote Jan 28, 2014 at 3:06 PM

This has my vote.

Inglor wrote Jan 30, 2014 at 11:40 PM

I felt I should add a better comment to this. I have been using EF since 4.0. Where the promise of disconnected POCO's in N-Tier started. We are now on version 6.0.2 and still no support for state management with disconnected entities. I have recently started a new project and decided to use EF 6. Please put this in the next release. I like entity framework, I have put a large amount time into learning it. I don't want to have to drop it in favour of n-Hibernate.

shkup wrote Feb 6, 2014 at 8:05 PM

If I would know that this will be the situation when I started my last project I wouldn't adopt it.
When you use the context in the server to load data and change it on the client (common scenario I would say) you have to write a lot of code at the server to find out what data have changed.
Not to mention that you should reload the original entity from the db for comparison purposes.
I have tried GraphDiff but it has bugs and you risk data corruption.

bjlewies wrote Mar 2, 2014 at 3:51 PM

This is, in my humble opinion, not a nice-to-have but an absolute must-have! I have to admit that I was caught unaware by this problem and as a result the delivery of one of my projects has been affected.

Were it not for the investment we have already made in terms of skills development and adoption of the technology, I would have summarily dropped Entity Framework altogether. I will be monitoring this issue closely - if this does not get fixed soon I will have no choice but to abandon EF and go with NHibernate.

I agree with the previous comments that this is basic functionality. I think the number of people who have voted on this issue does not reflect the severity and impact of the problem - people don't bother to investigate and report the problem... they merely give up and switch to "easier" alternatives like NHibernate.

granadaCoder wrote Apr 22, 2014 at 9:37 PM

I showed a Java guy (who uses Hibernate) my EF code for disconnected-graphs and handling all the Adding, Updating, and Deleting.

He said "It makes my eyes hurt".

I wrote the same code in NHibernate, and wow.

When I bring this up to people who are familiar with NHibernate, and they are like "EF doesn't have .Merge??? DEAL-BREAKER".

I have to agree. Manually mapping every object-graph,

4n41yz3r wrote May 5, 2014 at 5:02 PM

This thing would have saved me tons of unnecessary boilerplate code. Please, consider adding it.

jmoisespg wrote May 19, 2014 at 9:07 PM

I work in a large company with tons of developers, I like EF, but nobody here likes it just because it misses the "Merge" feature.
I think it's not a "MUST HAVE", it's like symbiotic of any ORM...
All of my coleagues have dropped EF6, and I'll be doing that soon if I don't see this feature set on next releases.
Besides it's so basic.

etosi wrote May 23, 2014 at 11:21 AM

Is this planned in EF 7 ?
Or we must go definitiveley to NHibernate...

ajcvickers wrote May 23, 2014 at 3:15 PM

@etosi and others: better support for disconnected entities is a key part of the plan for EF7, although we don't have specific details written down yet.

taraman wrote May 23, 2014 at 8:25 PM

do you have any due date to implement this very critical feature in EF 7
in my current project I am using GraphDiff, but in the next project I need to determine if I will continue with EF or go with NHibernate (which didn't work with it before)

so it will be a trade off between learning curve (Hibernate) versus write a mass code to handle related objects tracing

Mohamed Taraman

bhall wrote Jun 11, 2014 at 8:28 PM

Yeah this is why I have not used EF since it came out. It does not feel like a full ORM because of this. Every once in a while, I check to see if it has been added. It should be a warning when people find mapping a class to itself useful.

rajithakba wrote Jun 17, 2014 at 1:30 PM

Finally the wisdom almost - was extremely happy seeing this item in flight. Literally spent couple of days to understand the problem and possible solution.
Hope the team will include this feature in an upcoming release.

jimmymain wrote Aug 1, 2014 at 6:22 AM

I note that entity framework 7 is in the early stages of development.
please include the top voted feature into this next major release...

shaper wrote Sep 9, 2014 at 3:03 PM

Just found this issue here... It seems that GraphDiff saved me several hours of plumbing code... Thanks those guys!

Ramy99 wrote Sep 24, 2014 at 8:34 PM

After 2 days of plumbing code I'm happy to see this issue listed here....were aren't alone :D

_Dennis_ wrote Oct 10, 2014 at 2:57 PM

I'm wondering, how all those people, who write web applications, deal with EF? Are they writing custom merge logic for every object graph? Or they use something like Tracking Entities?

getfuzzy wrote Oct 16, 2014 at 10:48 PM

@_Dennis I wrote an EF6, Web API 2 Rest based service, and this turned out to initially be quite an issue. I took the approach of mocking EF, and using it directly in my controller without an intermediate repository layer between.

I first started by writing custom merge logic, which is a huge pain. Then I found GraphDiff, but as lots of EF stuff, its not very test friendly, so I wrapped it in my DbContext like so.
public virtual T GraphDiffUpdateGraph<T>(T entity, Expression<Func<IUpdateConfiguration<T>, object>> mapping) where T : class, new()
            return this.UpdateGraph(entity, mapping);
Then used it like this from my controller.
   public async Task<IHttpActionResult> PutAsync([FromBody]FluidModel model)
            if (!ModelState.IsValid) return BadRequest(ModelState);
            if (await TfContext.Fluids.FirstOrDefaultAsync(x => x.Id == model.Id) == null) return NotFound();
            var entity = ModelFactory.Create(model);
            TfContext.GraphDiffUpdateGraph(entity, f => f.OwnedCollection(p => p.FluidPoints));
            await TfContext.SaveChangesAsync();
            return Ok(ModelFactory.Create(entity));
Having it wrapped as virtual allowed me to at least mock that its being called in the controller. However, doing this, I still ended up writing several integration tests against LocalDb to ensure that GraphDiff was doing what I wanted. I didn't find examples for a few of the things that I wanted to do, and it took some fumbling with GraphDiff to figure out how to ensure things like nested collections could be handled.
 TfContext.GraphDiffUpdateGraph(entity, w => w.OwnedCollection(a => a.WorkStringAssemblies,
                                                                          c => c.OwnedCollection(wc => wc.Components)));
Overall though this seems to be working fairly well. I'll be paying close attention to EF 7, I'm hoping it makes building Rest controllers simpler, and more testable :) EF6 is a great jump in that direction though...

koo9koo9 wrote Oct 30, 2014 at 5:50 PM

EF s**ks because of lacking this feature.

dgxhubbard wrote Dec 9, 2014 at 9:13 PM

This is a very important feature and a bread and butter must have for developers. I have been developing using EF 6 for a bit and use disconnected objects, if I would have know that merge was not part of EF 6 I would have looked for an alternative solution. As it is I am using GraphDiff to overcome this problem, but will go another way if it is not included in EF 7.

seabizkit wrote Jan 6, 2015 at 5:12 PM

Hi All
Could someone explain with an example of what everyone is going on about, as i do not follow.

Are you saying that you would like:
Automapper type functionality built in to EF?
and your not using feature like UpdateModel(existDbModel, ViewModel) from MVC namespace for web projects.

From what i can gather everyone is going on about the functionality that Automapper give you.

Please help me understand.


getfuzzy wrote Jan 6, 2015 at 5:41 PM

@seabizkit, the functionality folks are talking about here is not what is provided by Automapper. Read this

this is the kind of functionality that is missing from Entity Framework. Hope that helps :)

westythedon wrote Jan 7, 2015 at 10:42 PM


For our web projects we use GraphDiff which we have slightly amended for our own purposes, essentially we mark an object state that has been modified and what properties on that object have changed this then gets passed down to our business layer method which goes through each object and applies the navigation update if this is a foreign key (associated entity) or list of objects (associated collection), it is very cumbersome and not ideal but it does the job to some affect although we have not tested this with a complex model as we have other ways of applying updates which involve more manual approach of changing object relationships.

I agree with a lot of the comments here, this has been very will hidden in terms of exposure and web sites that explain ef4 upto 6/7, we initially started with one application and built a framework up based on ef so other applications can leverage what had been done so far, once we got down to the details then this became a roadblock and if it wasn't for the GraphDiff component we would have wasted all our time and effort causing a major headache - to me personally i think this has been half done, you can change simple properties (scalar values) but cannot change relationships ? For an ORM this is quite a fundamental problem which should have been addressed in the next version (at the time it should have been 6) as all graph diff does is hit the database to get persisted version and then change the relationship (foreign key) to object - why ef team cannot do the same i don't know.

In answer to @seabizkit question, if you retrieve an object from datasource which has a relationship with another entity, close your connection (we use unit of works here) then change this entity to a newly created one on the fly, attach this newly created entity to your existing one so replacing your current one - open another connection to your datasource, attach both objects and then apply the you will see that the existing object does not have a relationship to your newly created one (even though when you look at changetracker the in-memory object does have this correctly set) but still has a relationship with your original object as the relationship state held in ef has not been changed to reflect the new object. If you do not close the connection during the change then it works fine as the changetracker can do this as it knows what has been changed via tracking, when disconnected we are trying to emulate this change.

Ideally it should be as simple as we pass an object to ef and it should go through navigation properties building up the structure of whats changed e.g. relationships added, updated or removed but this can be a complex process as graph diff highlights

seabizkit wrote Jan 8, 2015 at 7:17 PM

@getfuzy and @westythedon

If you setup your relationships with complex keys and not a surrogate Key.
and set up the EF relationship using the Fluid API.

Then you do get similar functionality to what you are describing.(although it can be improved)!

Then you can do something like say....

var Article = Db.context.Article.GetByID(12);

var posts = new List<Post>();
Post.Add(new Post{content = "Something interesting"})
Article.Posts = posts;

Where Post is an entity and there is a navigation get up. There is an articale someone explaining why it need to be a Complex Key.... its has to do with so that EF knows where it must delete or update a relationship.

I am sure you can extend this and make it more complex..... The irritating thing is it only works with Complex keys.

This this along the lines of what you are talking about?

hemanshubhojak wrote Feb 10, 2015 at 3:59 PM

In one of my projects we used EF 6 and were transferring the POCO classes over the wire. It was such a pain to merge it with EF that we finally decided to switch back to Nhibernate which makes it a breeze.

Also, we noticed that the overall performance increased considerably after switching to NH.

Although EF is improving with each release, I feel EF still has a long way to go.

BernardoG wrote Apr 15, 2015 at 9:59 AM

This is probably the most important feature missing in EF.
I agree that EF is improving, but without good support for disconnected entities, it´s almost useless.

mavo0013 wrote Apr 16, 2015 at 2:51 PM

Is someone even taking notice of this from the EF team? This is the highest-voted feature, so I would really like to see it in EF7...

seabizkit wrote Apr 17, 2015 at 10:00 AM

Could Someone Please write a simple Example of what they Mean or the Feature they are looking for.

I have post this before and still no one can actually say what this is..... Plz read my posts before this one.

Please give an actual example of what you are talking about when you say "disconnected entities"

as there are several examples online on how to handle this with EF which all make sense and the feature of what i would expect is there... so i am lost as to what everyone, is thinking is not there.


weitzhandler wrote Apr 19, 2015 at 7:31 AM


weitzhandler wrote Apr 19, 2015 at 7:38 AM

Any news?

I have a controller HttpPost action that accepts an entity and I want the following to happen:
  • Set the entity and all its properties as Modified
  • Compare the collection properties from store to the new collection received from client and perform the following:
    • Delete from store those that the client deleted
    • Modify all existing ones
    • Add all non-existing (i.e. ID == 0 etc.)
      Same should happen with navigation properties of 1-to-0-or-1 nav. properties.
Is there a normal solution for that already? Because currently this is a pain in the ass!

BBauer42 wrote Apr 22, 2015 at 3:23 PM

Is there any update on this? I'm starting a new large scale multi-tier application and trying to prove out the architecture. I've worked with EF4 in the past and am surprised this feature STILL DOESN"T EXIST. How is that possible? In trying to prove out my new architecture I am back at the "working with detachted entities" stumbling block. This is why I dropped EF4 and is why I am now going to begin the nHibernate learning curve. I can't wait to use .Merge in nHibernate, my nightmares will then stop.

seabizkit wrote Apr 22, 2015 at 4:08 PM

Ffs write an example

See past post by me

and then i maybe able to help!!!!!

SixSixTrample wrote Jun 30, 2015 at 5:12 PM


I have a TEAM


My UI allows me to edit the USERS on a TEAM.

I make an HTTP PUT call to my API with the udpated TEAM (let us say I added two users and removed one).

There is currently no easy way to say 'Update this TEAM with the new USER information'.

You have to set states, loop through properties, see which is ridiculous.

TysonStolarski wrote Oct 8, 2015 at 7:01 AM


This area of EF definetly needs improvement, especially given the push towards WebAPI and RESTful APIs.

uakdemir wrote Nov 27, 2015 at 12:59 PM

This is a joke - why are we even using ORM if we are to write its infrastructural code ourselves.

happynomad wrote May 6, 2016 at 2:22 AM

Has better support for disconnected entities been added to EF7 by any chance?