Bercovici Adrian
Bercovici Adrian

Reputation: 9360

EF Core Update throws exception only within transaction

I am using EF Core and i do not understand the following.I am using a typical update method and whenerver i am using it inside a transaction i get the following exception:

System.InvalidOperationException: 'The instance of entity type 'SegmentModel' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.'

The update method :

public void Update(T entity) {                     //Generic type
            var entry = this.context.Entry(entity); //specific DBContext
            if (entry.State == EntityState.Detached) {
                var attched = this.table.Attach(entity);
            }
            context.Entry(entity).State = EntityState.Modified;

        }

If i call this method alone , the update works.However when i use it in a transaction:

private async Task UpdateInTransaction(int id)
{
   var entry=this.repo.GetById(id);
   using(IDbContextTransaction tran=this.repo.BeginTransactionAsync()) //returns a 
   {
        //delete some entries
        this.repo.Update(entry);
   }
}

The interesting thing is that this thing worked until i inserted the GetById.That is the only method that involves my target entry before i call the Update.I have checked the state of the entry before updating in both cases ( normal update, and within transaction), and the state is in both Detached.

Why does update throw in this case?

Update From what i understand the problem stems from the fact that the target entity is first pulled from the database using GetById so its state is Attached.Then when i enter the Transaction and i Update i try to Attach it again and thus it fails. I can agree to this, but when i check with the debugger the state of the entity after the GetById but before the Update..its state is Detached.So even if i am attaching it should work. Where is the problem ?

Upvotes: 0

Views: 167

Answers (1)

Jonathan Busuttil
Jonathan Busuttil

Reputation: 493

That is because the same entity is being attached to the context twice. 1st when you do GetById and 2nd when you call your update method.

In your update method you do not need to attach the entity again, since it already is.

Upvotes: 1

Related Questions