Search code examples
asp.netentity-framework-4savepocoobject-graph

How to handle duplicates in disconnected object graph?


I'm having a problem updating a disconnected POCO model in an ASP.NET application.

Lets say we have the following model:

  1. Users
  2. Districts
  3. Orders

A user can be responsible for 0 or more districts, an order belongs to a district and a user can be the owner of an order.

When the user logs in the user and the related districts are loaded. Later the user loads an order, and sets himself as the owner of the order. The user(and related districts) and order(and related district) are loaded in two different calls with two different dbcontexts. When I save the order after the user has assigned himself to it. I get an exception that saying that acceptchanges cannot continue because the object's key values conflict with another object.

Which is not strange, since the same district can appear both in the list of districts the user is responsible and on the order.

I've searched high and low for a solution to this problem, but the answers I have found seems to be either:

  1. Don't load the related entities of one of the objects in my case that would be the districts of the user.
  2. Don't assign the user to the order by using the objects, just set the foreign key id on the order object.
  3. Use nHibernate since it apparently handles it.

I tried 1 and that works, but I feel this is wrong because I then either have to load the user without it's districts before relating it to the order, or do a shallow clone. This is fine for this simple case here, but the problem is that in my case district might appear several more times in the graph. Also it seems pointless since I have the objects so why not let me connected them and update the graph. The reason I need the entire graph for the order, is that I need to display all the information to the user. So since I got all the objects why should I need to either reload or shallow clone it to get this to work?

I tried using STE but I ran in to the same problem, since I cannot attach an object to a graph loaded by another context. So I am back at square 1.

I would assume that this is a common problem in anything but tutorial code. Yet, I cannot seem to find any good solution to this. Which makes me think that either I do not under any circumstance understand using POCOs/EF or I suck at using google to find an answer to this problem.

I've bought both of the "Programming Entity Framework" books from O'Reilly by Julia Lerman but cannot seem to find anything to solve my problem in those books either.

Is there anyone out there who can shed some light on how to handle graphs where some objects might be repeated and not necessarily loaded from the same context.


Solution

  • The reason why EF does not allow to have two entities with the same key being attached to a context is that EF cannot know which one is "valid". For example: You could have two District objects in your object graph, both with a key Id = 1, but the two have different Name property values. Which one represents the data that have to be saved to the database?

    Now, you could say that it doesn't matter if both objects haven't changed, you just want to attach them to a context in state Unchanged, maybe to establish a relationship to another entity. It is true in this special case that duplicates might not be a problem. But I think, it is simply too complex to deal with all situations and different states the objects could have to decide if duplicate objects are causing ambiguities or not.

    Anyway, EF implements a strict identity mapping between object reference identity and key property values and just doesn't allow to have more than one entity with a given key attached to a context.

    I don't think there is a general solution for this kind of problem. I can only add a few more ideas in addition to the solutions in your question:

    • Attach the User to the context you are loading the order in:

      context.Users.Attach(user); // attaches user AND user.Districts
      var order = context.Orders.Include("Districts")
          .Single(o => o.Id == someOrderId);
      // because the user's Districts are attached, no District with the same key
      // will be loaded again, EF will use the already attached Districts to
      // populate the order.Districts collection, thus avoiding duplicate Districts
      order.Owner = user;
      context.SaveChanges();
      // it should work without exception
      
    • Attach only the entities to the context you need in order to perform a special update:

      using (var context = new MyContext())
      {
          var order = new Order { Id = order.Id };
          context.Orders.Attach(order);
          var user = new User { Id = user.Id };
          context.Users.Attach(user);
      
          order.Owner = user;
      
          context.SaveChanges();
      }
      

      This would be enough to update the Owner relationship. You would not need the whole object graph for this procedure, you only need the correct primary key values of the entities the relationship has to be created for. It doesn't work that easy of course if you have more changes to save or don't know what exactly could have been changed.

    • Don't attach the object graph to the context at all. Instead load new entities from the database that represent the object graph currently stored in the database. Then update the loaded graph with your detached object graph and save the changes applied to the loaded (=attached) graph. An example of this procedure is shown here. It is safe and a very general pattern (but not generic) but it can be very complex for complex object graphs.

    • Traverse the object graph and replace the duplicate objects by a unique one, for example just the first one with type and key you have found. You could build a dictionary of unique objects that you lookup to replace the duplicates. An example is here.