[英]Entity Framework Repository Pattern in DAL, how to implement Update functions?
[英]How can I implement Entity Framework Repository Design Pattern in my C# DAL library?
我在我的项目中使用 EF 并且我想实现存储库设计模式,但我想要一个超类来处理Insert
/ Update
/ Delete
/ SaveChanges
方法以避免代码重复。
例如,我有这两个接口ICostTypeRepository
和IEmailRepository
:
public interface ICostTypeRepository : IDisposable
{
CostType GetCostTypeById(int pId);
CostType GetCostTypeByCode(string pCode);
IEnumerable<CostType> GetCostTypes();
void Insert(CostType pCostType);
void Update(CostType pCostType);
void Delete(CostType pCostType);
void SaveChanges();
}
public interface IEmailRepository : IDisposable
{
Email GetEmailByID(int pId);
IEnumerable<Email> GetEmails();
Email GetEmailByAdress(string pAddress);
void Insert(Email pEmail);
void Update(Email pEmail);
void Delete(Email pEmail);
void SaveChanges();
}
创建接口(及其在类中的实现)的最佳方法是什么,让我们称之为IDbOperations
, IDbOperations
包含 CRUD 方法?
类似的东西
public interface IDbOperations : IDisposable
{
void Insert(??);
void Update(??);
void Delete(??);
void SaveChanges();
}
这些 CRUD 方法将采用哪些参数?
叶片,
您需要的是通用存储库模式。 您必须在基类中编写基本操作代码,然后从中扩展所有存储库类。 在每个新的存储库类中,您可以创建更具体的方法。
这是通用存储库接口的示例
public interface IGenericRepository<T> where T : class {
IQueryable<T> GetAll();
IQueryable<T> FindBy(Expression<Func<T, bool>> predicate);
void Add(T entity);
void Delete(T entity);
void Edit(T entity);
void Save();
}
您可以像这样实现通用存储库:
public class GenericRepository<C, T> :
IGenericRepository<T> where T : class where C : DbContext, new() {
private C _entities = new C();
public C Context {
get { return _entities; }
set { _entities = value; }
}
public virtual IQueryable<T> GetAll() {
IQueryable<T> query = _entities.Set<T>();
return query;
}
public IQueryable<T> FindBy(System.Linq.Expressions.Expression<Func<T, bool>> predicate) {
IQueryable<T> query = _entities.Set<T>().Where(predicate);
return query;
}
public virtual void Add(T entity) {
_entities.Set<T>().Add(entity);
}
public virtual void Delete(T entity) {
_entities.Set<T>().Remove(entity);
}
public virtual void Edit(T entity) {
_entities.Entry(entity).State = System.Data.EntityState.Modified;
}
public virtual void Save() {
_entities.SaveChanges();
}
}
现在你有了 GenericRepository 类,让 FooRepository 扩展它并添加特定的方法(如果需要),如下所示:
public class FooRepository :
GenericRepository<FooBarEntities, Foo>, IFooRepository {
public Foo GetSingle(int fooId) {
var query = GetAll().FirstOrDefault(x => x.FooId == fooId);
return query;
}
}
您应该阅读有关工作单元模式的信息。 存储库模式很有意义。 请阅读 Microsoft 的这篇文章。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.