How can I avoid Tracking error when deleting the same ID twice?

0

I implemented a simple Delete method in my ServiceStack Service class as follows...

        public void Delete(DeleteCompany d)
        {
           
            Company c = new Company();
            c = ctx.Companies.AsNoTracking().FirstOrDefault(m => m.id == d.id);
            if (c == null)
            {
                return;
            }

            ctx.Companies.Remove(c);                
            ctx.SaveChanges();
                      
        }

ctx is populated via Dependency Injection.

This works great the first time I delete an object. But if I create another object with the same ID and then attempt to delete it, I get this exception...

System.InvalidOperationException HResult=0x80131509 Message=The instance of entity type 'Company' 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. Source=Microsoft.EntityFrameworkCore
StackTrace: at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.IdentityMap1.ThrowIdentityConflict(InternalEntityEntry entry) at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.IdentityMap1.Add(TKey key, InternalEntityEntry entry, Boolean updateDuplicate) at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.IdentityMap1.Add(TKey key, InternalEntityEntry entry) at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.NullableKeyIdentityMap1.Add(InternalEntityEntry entry) at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.StartTracking(InternalEntityEntry entry) at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.SetEntityState(EntityState oldState, EntityState newState, Boolean acceptChanges, Boolean modifyProperties) at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.SetEntityState(EntityState entityState, Boolean acceptChanges, Boolean modifyProperties, Nullable1 forceStateWhenUnknownKey) at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityGraphAttacher.PaintAction(EntityEntryGraphNode1 node) at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityEntryGraphIterator.TraverseGraph[TState](EntityEntryGraphNode1 node, Func2 handleNode) at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityGraphAttacher.AttachGraph(InternalEntityEntry rootEntry, EntityState targetState, EntityState storeGeneratedWithKeySetTargetState, Boolean forceStateWhenUnknownKey) at Microsoft.EntityFrameworkCore.Internal.InternalDbSet1.SetEntityState(InternalEntityEntry entry, EntityState entityState) at Microsoft.EntityFrameworkCore.Internal.InternalDbSet1.Remove(TEntity entity) at WebApp.ServiceInterface.CompanyService.Delete(DeleteCompany d) in C:\Projects\NCMSAudit\ServiceStack\NCMSProgram\NCMSProgram.ServiceInterface\CompanyService.cs:line 81 at ServiceStack.Host.ServiceExec1.<>c__DisplayClass3_0.<CreateExecFn>b__0(Object service, Object request) in C:\BuildAgent\work\3481147c480f4a2f\src\ServiceStack\Host\ServiceExec.cs:line 177 at ServiceStack.Host.ServiceRunner1.d__15.MoveNext() in C:\BuildAgent\work\3481147c480f4a2f\src\ServiceStack\Host\ServiceRunner.cs:line 134

How can I improve my code so I don't get this exception?

entity-framework-core
servicestack
asked on Stack Overflow Jan 7, 2021 by Mike W

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0