Naveed Khan
Naveed Khan

Reputation: 81

Unable to delete using dbSet - Entity Framework

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.

Upvotes: 0

Views: 980

Answers (2)

Emre Kabaoglu
Emre Kabaoglu

Reputation: 13146

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.

Upvotes: 2

sebu
sebu

Reputation: 2954

Try this.

DbContext.Entry(entity).State = EntityState.Deleted;
DbContext.SaveChanges();

Upvotes: 1

Related Questions