C#存储库设计问题
发布时间:2020-12-15 23:56:34 所属栏目:百科 来源:网络整理
导读:我正在为MVC 2 Web应用程序编写EF4数据层,我需要有关选择继承与抽象基类的建议.我的存储库在’generic repo’结构之后运行良好,但现在我想添加“Audit”功能,该功能在每次执行CRUD操作时都会记录. 这是我到目前为止使用的合同: public interface IRepositor
|
我正在为MVC 2 Web应用程序编写EF4数据层,我需要有关选择继承与抽象基类的建议.我的存储库在’generic repo’结构之后运行良好,但现在我想添加“Audit”功能,该功能在每次执行CRUD操作时都会记录.
这是我到目前为止使用的合同: public interface IRepository<T>
{
void Create(T entity);
void Update(T entity);
void Delete(Func<T,bool> predicate);
T Get(Func<T,bool> predicate);
IQueryable<T> Query();
}
我的回购实现看起来像这样: sealed class EFRepository<TEntity> : IRepository<TEntity>
where TEntity : EntityObject
{
ObjectContext _context;
ObjectSet<TEntity> _entitySet;
public EFRepository(ObjectContext context)
{
_context = context;
_entitySet = _context.CreateObjectSet<TEntity>();
}
public void Create(TEntity entity)
{
_entitySet.AddObject(entity);
_context.SaveChanges();
}
public void Update(TEntity entity)
{
_entitySet.UpdateObject(entity);
_context.SaveChanges();
}
public void Delete(Func<TEntity,bool> predicate)
{
TEntity entity = _entitySet.Single(predicate);
_entitySet.DeleteObject(entity);
_context.SaveChanges();
}
public TEntity Get(Func<TEntity,bool> predicate)
{
return _entitySet.SingleOrDefault(predicate);
}
public IQueryable<TEntity> Query()
{
return _entitySet;
}
}
我想创建AuditableRepository< T>的概念.我应该像这样创建它: interface IAuditable<T> interface IRepository<T> AuditableRepository<T> : IRepository<T>,IAuditable<T> EFRepository<T> : AuditableRepository<T> 或者像这样更好: interface IAuditable<T> interface IRepository<T> EFRepository<T> : IRepository<T>,IAuditable<T> 甚至: interface IAuditable<T> interface IRepository<T> AuditableRepository<T> : IRepository<T>,IAuditable<T> EFRepository<T> : IRepository<T> AuditableEFRepository<T> : AuditableRepository<T> 并非所有的EFRepositories都需要审核.我该怎么办? 解决方法
这是另一种可能性(使用Decorator对象向现有存储库添加其他功能):
public sealed class Auditor<T> : IRepository<T>
{
private readonly IRepository<T> _repository;
public Auditor(IRepository<T> repository)
{
_repository = repository;
}
public void Create(T entity)
{
//Auditing here...
_repository.Create(entity);
}
//And so on for other methods...
}
使用Decorator添加其他功能的好处是,它可以避免在您考虑使用审计的某些存储库时开始看到的组合爆炸,有些没有,有些使用EF,有些则没有.每一个可能适用或可能不适用的新功能都会逐渐变得更糟,通常最终会转变为配置标志和混乱的内部分支. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- nor flash、nand flash 、sdram的区别
- 解决cocos2dx CCArmature动画在部分型号的安卓手机上播放不
- VB.NET机房收费系统导出Excel
- [Swift通天遁地]三、手势与图表-(4)3DTouch功能在项目中的应
- c – 模板类,函数专业化
- 详解给Vue2路由导航钩子和axios拦截器做个封装
- cocos2d-x 3.4 eclipse android 编译是出现WindowsError: [
- 无论如何导出PostgreSQL架构压缩?
- PostgreSQL服务过程中的那些事二:Pg服务进程处理简单查询一
- actionscript-3 – 如何使用Flex / ActionScript 3通过Sock
