简体   繁体   English

由于跟踪问题,添加后无法删除项目

[英]Can't delete item after being added due to tracking issues

I am adding an entity using the Upsert method below and deleting it after using the Delete method.我正在使用下面的 Upsert 方法添加一个实体,并在使用 Delete 方法后将其删除。

However this throws on the this.Items.Remove(item) line with the below error.但是,这会在this.Items.Remove(item)行上引发以下错误。

public async Task<TEntity> Upsert(TEntity item)
{
   var entity = this.Context.Update(item);
   await this.SaveChangesAsync();
   return entity.Entity;
}

public async Task Delete(TEntity item)
{
   this.Items.Remove(item);
   await this.SaveChangesAsync();
}

Error:错误:

The instance of entity type 'x' cannot be tracked because another instance with the key value '{Id: 204}' is already being tracked.无法跟踪实体类型“x”的实例,因为已在跟踪另一个具有键值“{Id: 204}”的实例。 When attaching existing entities, ensure that only one entity instance with a given key value is attached.附加现有实体时,请确保仅附加一个具有给定键值的实体实例。

I think the issue here is that, when I add an entity, it is added as tracked and when I try to delete, it can't be deleted while being tracked?我认为这里的问题是,当我添加一个实体时,它被添加为已跟踪,而当我尝试删除时,它在被跟踪时无法删除?

Any help vastly appreciated, I'm still new to Entity Framework.非常感谢任何帮助,我对 Entity Framework 还是很陌生。

If you Edit or Remove an record form DataBase , the ChaneTracker change the state of entity to Modified or Removed In Current Context , And if you read the data from the database ( In Current Context ), because the entities are tracked by ChangeTracker an error occurs because in the ChangeTracker can't exist two record with a key at the same time.如果您Edit or Remove an record form DataBase ,则 ChaneTracker 将实体的ChaneTracker更改为ModifiedRemoved In Current Context ,并且如果您从数据库中读取数据( In Current Context ),因为ChangeTracker跟踪实体会发生错误因为在ChangeTracker中不能同时存在两个带有键的记录。 so you must clear tracked entities from ChangeTracker .因此您必须从ChangeTracker中清除跟踪的实体。

Add this code after await this.SaveChangesAsync();await this.SaveChangesAsync();之后添加此代码to detach records from ChangeTrackerChangeTracker中分离记录

foreach (var entity in this.Context.ChangeTracker.Entries())
{
     entity.State = System.Data.Entity.EntityState.Detached;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM