不久前,我使用 linq to sql 创建了存储库和服务,但我很难理解它。我终于明白了,但现在我正在尝试做同样的事情,但使用 Code First EF。我对这如何与代码一起工作感到困惑。如果我有一个存储库,我可以只传入一个类对象并具有 select() 等...这是如何交互的,或者我如何将它连接到/一个 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
{
}
最佳答案
这是一个Tutorial EF 中的 Repository 和 UnitOfWork 来自 ASP.Net .希望这有帮助。 (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);
}
...
}
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();
}
....
}
Controller :
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());
}
....
}
关于c# - 使用 Entity Framework Code First 4.3 创建存储库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9677745/