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

夙愿已清 提交于 2019-12-06 05:10:36

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)

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.

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