0

I use repository with Update method. In this method I need to check some conditions, finding updating entity in DB before actual update. I use one context for both - Find and Update operations inside one transaction. But when I try to update entity I get an exception:

"Attaching an entity of type 'MyNamespace.MyEntityType' failed because another entity of the same type already has the same primary key value"

public void Update(SomeType entity)
{
    using (var context = new MyEntities())
    {
        using (var transaction = context.Database.BeginTransaction(IsolationLevel.RepeatableRead))
        {
            try
            {
                // check conditions
                var root = context.MyEntitySet
                    .Where(e => e.Parent == null); // entity.Parent == null
                if(root ...)
                    ; // return

                // HERE I got an error described above
                context.Entry(entity).State = EntityState.Modified;

                context.SaveChanges();
                transaction.Commit();
            }
            catch
            {
                transaction.Rollback();
                throw;
            }
        }
    }
}

I need to load entity with same Id from DB first, check some conditions and if ok, update entity. But after "Get" entity attaches to ChangeTracker with "Detached" state and when I try to change state to "Modified" I got an error.

I've already tried:

if (IsAttached(entity, out attachedEntity))
    context.Entry(attachedEntity).CurrentValues.SetValues(entity);

but my original entity object stays unchanged with DB generated values. State = EntityState.Modified works as I need, but how can I remove preloaded entity from ChangeTracker?

  • I think you can simply do `context.MyEntitySet.AsNoTracking()`, but it's hard to piece together what you're actually doing. – Gert Arnold Sep 04 '14 at 20:02
  • I can't understand how AsNoTracking() can help me and how to use in here. What I need to do - is read entity and then update entity with new values within one context instance – Anton Korzhenevskiy Sep 04 '14 at 20:37
  • You only seem to read (and not modify) `root`, so it doesn't need to be attached. From what I can see, `root` is the only possible conflicting entity. You don't show enough. For one, it's not clear how you modify `entity`'s values. – Gert Arnold Sep 04 '14 at 20:46
  • You might have a look at my answer on [ASP.NET MVC - Attaching an entity of type 'MODELNAME' failed because another entity of the same type already has the same primary key value](http://stackoverflow.com/questions/23201907/asp-net-mvc-attaching-an-entity-of-type-modelname-failed-because-another-ent/39557606#39557606). – Murat Yıldız Sep 18 '16 at 13:10

0 Answers0