5 .net asp.net-mvc entity-framework
我刚刚看到了GenericRepository的实现:
namespace ContosoUniversity.DAL
{
public class GenericRepository<TEntity> where TEntity : class
{
internal SchoolContext context;
internal DbSet<TEntity> dbSet;
public GenericRepository(SchoolContext context)
{
this.context = context;
this.dbSet = context.Set<TEntity>();
}
public virtual IEnumerable<TEntity> Get(
Expression<Func<TEntity, bool>> filter = null,
Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
string includeProperties = "")
{
IQueryable<TEntity> query = dbSet;
if (filter != null)
{
query = query.Where(filter);
}
foreach (var includeProperty in includeProperties.Split
(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
query = query.Include(includeProperty);
}
if (orderBy != null)
{
return orderBy(query).ToList();
}
else
{
return query.ToList();
}
}
public virtual TEntity GetByID(object id)
{
return dbSet.Find(id);
}
public virtual void Insert(TEntity entity)
{
dbSet.Add(entity);
}
public virtual void Delete(object id)
{
TEntity entityToDelete = dbSet.Find(id);
Delete(entityToDelete);
}
public virtual void Delete(TEntity entityToDelete)
{
if (context.Entry(entityToDelete).State == EntityState.Detached)
{
dbSet.Attach(entityToDelete);
}
dbSet.Remove(entityToDelete);
}
public virtual void Update(TEntity entityToUpdate)
{
dbSet.Attach(entityToUpdate);
context.Entry(entityToUpdate).State = EntityState.Modified;
}
}
}
Run Code Online (Sandbox Code Playgroud)
这里:http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/implementing-the-repository-and-unit-of-work-patterns-in-an-asp- net-mvc-application 我认为这很好,但我想问你一个问题.这种方法的优缺点是单独实现(每个实体存储库在单独的类中)?
这比其他任何事情都更个人化。就我个人而言,我不喜欢“存储库”这个术语,因为它太通用并且存储库的含义/目的已经丢失。我发现存储库通常是通用且重复的,就好像每个实体都需要它自己的存储库一样。然后存储库获得太多一次性查询方法。很快你就会得到一个用于数据访问的神级。这是我的经历。
使用通用存储库,您可以使用继承来子类化特定实体以进行开关查询。与继承相比,我更喜欢组合,这是我避免使用存储库这一术语/使用的另一个原因。
相反,我喜欢将数据访问视为查询(读取)和命令(写入)对象。其中每个对象都有 1 个方法来检索数据的特定投影(查询)或修改持久数据(命令)。
最后,只要您和您的团队了解架构并且代码是可维护的,您就有了一个可靠的解决方案。这并不是真正的好或坏。