How can I use Entity Framework 6 and my repository to delete multiple records?

守給你的承諾、 提交于 2019-12-08 01:00:59

问题


I am using Entity Framework 6 and I have a repository looking like the following with the Add and Update methods removed to make it shorter:

 public class GenericRepository<T> : IRepository<T> where T : class
{
    public GenericRepository(DbContext dbContext)
    {
        if (dbContext == null) 
            throw new ArgumentNullException("An instance of DbContext is required to use this repository", "context");
        DbContext = dbContext;
        DbSet = DbContext.Set<T>();
    }

    protected DbContext DbContext { get; set; }

    protected DbSet<T> DbSet { get; set; }

    public virtual IQueryable<T> Find(Expression<Func<T, bool>> predicate)
    {
        return DbSet.Where<T>(predicate);
    }

    public virtual IQueryable<T> GetAll()
    {
        return DbSet;
    }

    public virtual T GetById(int id)
    {
        //return DbSet.FirstOrDefault(PredicateBuilder.GetByIdPredicate<T>(id));
        return DbSet.Find(id);
    }

    public virtual void Delete(T entity)
    {
        DbEntityEntry dbEntityEntry = DbContext.Entry(entity);
        if (dbEntityEntry.State != EntityState.Deleted)
        {
            dbEntityEntry.State = EntityState.Deleted;
        }
        else
        {
            DbSet.Attach(entity);
            DbSet.Remove(entity);
        }
    }

    public virtual void Delete(int id)
    {
        var entity = GetById(id);
        if (entity == null) return; // not found; assume already deleted.
        Delete(entity);
    }
}

In my controller I call the repository like this:

    public HttpResponseMessage DeleteTest(int id)
    {
        Test test = _uow.Tests.GetById(id);
        if (test == null)
        {
            return Request.CreateResponse(HttpStatusCode.NotFound);
        }
        try
        {
            _uow.Tests.Delete(test);
            _uow.Commit();
            return Request.CreateResponse(HttpStatusCode.OK);
        }
        catch (Exception ex)
        {
            return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
        }
    }

This works for a single test but how can I delete for example all tests that have an examId column value of 1 being that examId is one of the columns in the Test table.


回答1:


You can create another delete method in your generic repository class, see below:

    public virtual void Delete(Expression<Func<T, bool>> predicate)
    {
        IQueryable<T> query = DbSet.Where(predicate).AsQueryable();
        foreach (T obj in query)
        {
            DbSet.Remove(obj);
        }
    }

Then you can use it like below, it will delete all records which Id equalsid.

  _uow.Test.Delete(n => n.Id = id)



回答2:


I'm not sure if EF is able to handle multiple delete now given a certain value, but the last time I did this I had to resort to a loop.

public HttpResponseMessage DeleteTest(int id)
{
  var testList = _uow.Tests.GetAll().Where(o => o.Id == id);
  if (testList.Count() == 0)
  {
      return Request.CreateResponse(HttpStatusCode.NotFound);
  }
  try
  {
      foreach (var test in testList)
      {
        _uow.Tests.Delete(test);
      }
      _uow.Commit();
      return Request.CreateResponse(HttpStatusCode.OK);
  }
  catch (Exception ex)
  {
      return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
  }
}

If the "test" table is a foreign table linked to a primary table on the "ID" column, you may want to consider doing a cascading delete in this case.




回答3:


You can use RemoveRange()

public virtual void Delete(Expression<Func<T,bool>> predicate)
{
   var query = Context.Set<T>().Where(predicate);
   Context.Set<T>().RemoveRange(query);
}


来源:https://stackoverflow.com/questions/20812473/how-can-i-use-entity-framework-6-and-my-repository-to-delete-multiple-records

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!