Unable to delete using dbSet - Entity Framework

时间:2017-12-18 05:53:55

标签: c# wpf entity-framework datacontext dbset

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:

enter image description here

Then I used another method like this:

    DbContext.ChangeTracker.DetectChanges();
        DbContext.Entry(entity).State = EntityState.Deleted;

and now the error is something like: enter image description here

Thanks in advance.

2 个答案:

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