Search code examples
asp.netobjectdatasourceentitydatasource

An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key


Possible Duplicate:
. The An object with the same key already exists in the ObjectStateManagerObjectStateManager cannot track multiple objects with the same key.

I have used Entity Framework with ObjectDataSource for GridView. while i have tried with updatemethod i got the run time error message

An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.

Here is my aspx file code:

    <asp:ObjectDataSource ID="odsCustomerList" runat="server" DataObjectTypeName="EF.POCO.Customer"
                TypeName="EF.BusinessLayer.CustomerMaster" SelectMethod="ReadAllCustomer" SortParameterName="sortExpression"
                ConflictDetection="CompareAllValues" OldValuesParameterFormatString="orig{0}"  
                UpdateMethod="UpdateCustomer" DeleteMethod="DeleteCustomer">
    </asp:ObjectDataSource>

Here is my Code File of DA Layer

     public void UpdateCustomer(Customer customer, Customer origCustomer)
    {
        try
        {

            BusinessEntityBase.Entities.Customers.MergeOption = System.Data.Objects.MergeOption.NoTracking;
            BusinessEntityBase.Entities.Customers.Attach(origCustomer);
            BusinessEntityBase.Entities.ApplyCurrentValues("Customer", customer);
            BusinessEntityBase.Entities.SaveChanges();
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

Is there anyone who can help to sort out this issue ?


Solution

  • How are you managing the context (ObjectContext) - does BusinessEntityBase.Entities is shared across multiple requests? This can be an issue - because object retrieved from one request can conflict when you are trying to update the object from other request (and so attach will fail). See this link for possible solution: http://dotnetslackers.com/articles/ado_net/Managing-Entity-Framework-ObjectContext-lifespan-and-scope-in-n-layered-ASP-NET-applications.aspx