Entity Framework Code-First: "ObjectStateManager cannot track multiple objects with the same key."

I had a problem with Entity Framework code - first in MVC3. I am removing this exception:

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

This appeals to SO many times, but I am having problems using any of the suggested solutions in my situation.

Here is a sample code:

FestORM.SaleMethod method = new FestORM.SaleMethod
{
    Id = 2,
    Name = "Test Sale Method"
};
FestContext context = new FestContext();

//everything works without this line:
string thisQueryWillMessThingsUp = 
    context.SaleMethods.Where(m => m.Id == 2).Single().Name;

context.Entry(method).State = System.Data.EntityState.Modified;
 context.SaveChanges();

EDITED clarify: I'm trying to update an object that already exists in the database.

, . , , , . ObjectStateManager, . , : , ObjectStateManager, .

FWIW, , :

public void Update(T entity)
{
    //works ONLY when entity is not tracked by ObjectStateManager
    _context.Entry(entity).State = System.Data.EntityState.Modified; 
}

public void SaveChanges()
{
    _context.SaveChanges();
}

? ...

+5
2

,

string thisQueryWillMessThingsUp =  
    context.SaleMethods.Where(m => m.Id == 2).Single().Name; 

SaleMethod ,

context.Entry(method).State = System.Data.EntityState.Modified;

. , EF , . , .

- , , , :

string thisQueryWillMessThingsUp =           
    context.SaleMethods.Where(m => m.Id == 2).AsNoTracking().Single().Name; 

, , , , - :

context.Entry(method).State = System.Data.EntityState.Modified;

, , - , , SaveChanges . . - Property, - :

var salesMethod = context.SaleMethods.Find(2); // Basically equivalent to your query
context.Entry(salesMethod).Property(e => e.Name).CurrentValue = newName;
context.Entry(salesMethod).Property(e => e.SomeOtherProp).CurrentValue = newOtherValue;
context.SaveChanges();

, :

http://blogs.msdn.com/b/adonet/archive/2011/01/29/using-dbcontext-in-ef-feature-ctp5-part-4-add-attach-and-entity-states.aspx

http://blogs.msdn.com/b/adonet/archive/2011/01/30/using-dbcontext-in-ef-feature-ctp5-part-5-working-with-property-values.aspx

+12

, :

//everything works without this line:
string thisQueryWillMessThingsUp = context.SaleMethods.Where(m => m.Id == 2).Single().Name;

, , , , . , , ..

public abstract class BaseClass
{
     public int Id { get; set; }
}

public class Repository<T> where T : BaseClass
{
 .....
    public void Update(T entity)
    {        
        _context.Entry(entity).State = entity.Id == 0 ? System.Data.EntityState.Added : System.Data.EntityState.Modified; 
    }
}

SaleMethod . , SaleMethod 2, SaleMethod Id 2. , , SaleMethod 2 ObjectStateManager.

+1

All Articles