I am using EF6 and I am trying to delete an entity like this:
public virtual void Delete(TEntity entity)
{
DbContext.Configuration.ValidateOnSaveEnabled = false;
DbContext.ChangeTracker.DetectChanges();
_dbSet.Remove(entity);
}
But it's giving me error like this:
Then I used another method like this:
DbContext.ChangeTracker.DetectChanges();
DbContext.Entry(entity).State = EntityState.Deleted;
and now the error is something like:
Thanks in advance.
答案 0 :(得分:2)
You can't remove the entity which doesn't exist in ObjectStateManager
. Try to attach it before trying to remove;
public virtual void Delete(TEntity entity)
{
DbContext.Configuration.ValidateOnSaveEnabled = false;
DbContext.ChangeTracker.DetectChanges();
var entry = DbContext.Entry(entity);
if (entry.State == EntityState.Detached)
_dbSet.Attach(entity);
_dbSet.Remove(entity);
}
Also, I don't know how are you fetching the entity instance but don't use .AsNoTracking()
if you will modify or remove them.
答案 1 :(得分:1)
Try this.
DbContext.Entry(entity).State = EntityState.Deleted;
DbContext.SaveChanges();