The instance of entity type cannot be tracked because another instance of this type with the same key is already being tracked

asp.net c# entity-framework

Popular Answer

You can also Detach the "local" entry and Attach your Updated Entry before Saving without Overriding EF Track System:

// 
var local = _context.Set<YourEntity>()
    .Local
    .FirstOrDefault(entry => entry.Id.Equals(entryId));

// check if local is not null 
if (local != null)
{
    // detach
    _context.Entry(local).State = EntityState.Detached;
}
// set Modified flag in your entry
_context.Entry(entryToUpdate).State = EntityState.Modified;

// save 
_context.SaveChanges();

UPDATE: You can provide an extension method to prevent code duplication:

public static void DetachLocal<T>(this DbContext context, T t, string entryId) 
    where T : class, IIdentifier 
{
    var local = context.Set<T>()
        .Local
        .FirstOrDefault(entry => entry.Id.Equals(entryId));
    if (!local.IsNull())
    {
        context.Entry(local).State = EntityState.Detached;
    }
    context.Entry(t).State = EntityState.Modified;
}

My IIdentifier interface only has oneId string attribute.

You can apply this technique to your context regardless of your Entity:

_context.DetachLocal(tmodel, id);
_context.SaveChanges();
46
12/3/2019 4:33:42 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow