Home > Enterprise >  EF Core Remove by ID
EF Core Remove by ID

Time:04-23

I was trying to delete a record - but I'm getting this error:

The instance of entity type 'Users' 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

I tried the following ways, but all failed with the same error.

var Users = context.Users.Where(x => x.Id.Equals(UsersId));
context.Users.RemoveRange(Users);
await context.SaveChangesAsync();

var Users = await context.Users.AsNoTracking().FirstOrDefaultAsync(x => x.Id.Equals(UsersId));
context.Users.Remove(Users);
await context.SaveChangesAsync();

var Users = new Users() {Id = UsersId};
context.Users.Attach(Users);
context.Users.Remove(Users);
await context.SaveChangesAsync();

CodePudding user response:

The presented code is not enought for understanding the root cause.
If it is a web application you might have issue with sharing same database context accross all http requests. But db context should be uniq for each http request. Avoid to make it singleton.
If it is a console application - you might have an issue with a configuration.
Option 1:
Try to do this:

Context.Entry(entity).State = EntityState.Detached

This is not a solution, but just for troubleshooting.
Option 2:
Try to do a very simple Console application with your database context and run your first code snippet - it should work.

Can be usefull:
instance of entity type cannot be tracked because another instance with same key value is tracked

  • Related