【发布时间】:2013-12-28 08:19:43
【问题描述】:
我正在使用 Entity Framework 6,并且我有一个如下所示的存储库,其中删除了 Add 和 Update 方法以使其更短:
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);
}
}
在我的控制器中,我这样调用存储库:
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);
}
}
这适用于单个测试,但我如何删除例如所有examId 列值为1 的测试 该examId 是Test 表中的列之一。
【问题讨论】:
-
你的意思是
_uow.Tests.Where(t => t.Id == id).Delete()? -
但是我的存储库没有 .Where :-(
-
使
GetById返回Test的列表,而不是一个测试。让它返回return Test.Where(t => t.Id == id) -
其实EF本身就是一个仓库。将存储库模式与 EF 一起使用就像添加另一个不必要的抽象层。
-
EF6 引入了
DbSet.RemoveRangemethod。同样,还有一个AddRange方法。
标签: asp.net-mvc entity-framework entity-framework-6