locked
Another 'ObjectStateManager already contains an Entity with the same key. Cannot have multiple entities with the same EntityKey in Object' question RRS feed

  • Question

  • Hi,
    At my work, we are starting using MVC3 with EF 4.1 ( POCO Classes ).
    This week, we have faced a problem and couldnt find any solution for it so far.
    To make things clear, I'm making up a simpler scenario to represent the problem:
    public class Order 
    {
    public Customer customer { get; set; }
    public Address deliverTo { get; set; }
    ...  other properties and methods
    }
    
    public class Address
    {
    ...
    public State state { get; set; }
    ...
    }
    
    Public Class State
    {
    public int Id
    public string name { get; set; }
    }
    
    public Class Customer
    {
    ...
    public Address address { get; set; }
    ...
    }
    

    So we sent a new order to be filled out in a view, including a new Customer info ( I know it may not make sense, but its just an example ).
    After the entire new order has been filled out, we receive it in a post action method like this :
    [HttpPost]
    public ActionResult EditOrder ( Order order )
    {
        If (ModelState.IsValid)
       {
          context.Orders.Entry(order);
          context.SaveChanges();   <-- this is where the error happens.
       }
    }
    
     
    The error is : 'ObjectStateManager already contains an Entity with the same key. Cannot have multiple entities with the same EntityKey in Object'
    After looking at the order graph, we realized that once both Customer Address and Order Address are filled out in the view, there are two objects State with the same Id ( both representing selected states from DropDownListFor in the view ). So when we try to put the order object into the context, the first state runs OK, but the next one already exists and then the error happens.
    Is there a way to solve this problem without having to save the Order and Customer separate in a first step and then reference each other and save them secondly?
    How to make the context understand that the states should be the same existing object ( only a reference to an already existing state )?
    Thanks,
    Paulo
     
     
     
     
     
    Sunday, September 11, 2011 7:01 PM

Answers