TMa*_*Man 5 c# repository asp.net-mvc-3
不久前,我使用linq to sql创建了存储库和服务,我很难理解它.我终于明白了,但现在我正在尝试使用Code First EF做同样的事情.我首先对代码的工作方式感到困惑.如果我有一个存储库,我只能传入一个类对象并有select(),ect ......这是如何交互的,或者我如何将它连接到/ DbContext?如果有人可以指出我正确的方向或给我一些建议,将不胜感激.谷歌上的这个东西并不多,因为它仍然是一个相对较新的模式.
如何使用/我会使用DbSet吗?这些存储库很酷但令人困惑.
public class IRepository<T> : IDisposable
where T : class, new()
{
IQueryable<T> Select();
IQueryable<T> SelectWith(params Expression<Func<T, object>>[] includeProperties);
T GetById(int id);
T GetByIdWith(int id, params Expression<Func<T, object>>[] includeProperties);
void InsertOnCommit(T model);
void DeleteOnCommit(T model);
}
public class DataContext : DbContext
{
}
Run Code Online (Sandbox Code Playgroud)
这是ASP.Net的 EF中的Repository和UnitOfWork 教程.希望这有帮助.(UnitOfWork是为了确保多个存储库共享相同的DataContext)
通用存储库:
public class GenericRepository<TEntity> where TEntity : class
{
internal SchoolDBContext context;
internal DbSet<TEntity> dbSet;
public GenericRepository(SchoolDBContext 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 = "")
{
...
}
public virtual TEntity GetByID(object id)
{
return dbSet.Find(id);
}
public virtual void Insert(TEntity entity)
{
dbSet.Add(entity);
}
...
}
Run Code Online (Sandbox Code Playgroud)
UnitOfWork:调用Save()方法更新存储库中的所有更改.
public class UnitOfWork : IDisposable
{
private SchoolDBContext context = new SchoolDBContext();
private GenericRepository<Department> departmentRepository;
public GenericRepository<Department> DepartmentRepository
{
get
{
if (this.departmentRepository == null)
{
this.departmentRepository = new GenericRepository<Department>(context);
}
return departmentRepository;
}
}
public void Save()
{
context.SaveChanges();
}
....
}
Run Code Online (Sandbox Code Playgroud)
控制器:
public class CourseController : Controller
{
private UnitOfWork unitOfWork = new UnitOfWork();
//
// GET: /Course/
public ViewResult Index()
{
var courses = unitOfWork.CourseRepository.Get(includeProperties: "Department");
return View(courses.ToList());
}
....
}
Run Code Online (Sandbox Code Playgroud)