EF Core 按 ID 删除

EF Core Remove by ID

我试图删除一条记录 - 但出现此错误:

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

我尝试了以下方法,但均失败并出现相同的错误。

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();

提供的代码不足以理解根本原因。
如果它是一个 Web 应用程序,您可能会遇到跨所有 http 请求共享相同数据库上下文的问题。但是对于每个 http 请求,数据库上下文应该是唯一的。 避免使其成为单例。
如果它是控制台应用程序 - 您可能遇到配置问题。
选项 1:
尝试这样做:

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

这不是解决方案,只是为了解决问题。
选项 2:
尝试使用您的数据库上下文和 运行 您的第一个代码片段来做一个非常简单的控制台应用程序 - 它应该可以工作。

很有用
instance of entity type cannot be tracked because another instance with same key value is tracked