您可以利用各种数据访问技术来利用存储库。一个
存储库是对现有数据访问帮助器/服务的抽象,允许将业务逻辑与数据访问层解耦。存储库与查询一起使用以启用过滤。它通常与
工作单元一起使用,将更改存储回数据库。
存储库至少具备以下功能:
1. 按键获取对象操作
2. 获取所有对象操作
3. 按查询获取第一个对象操作
4. 按查询获取对象操作
下面是一个非常简单的例子:)
A. 在
Common中定义了
Product类:
public class Product
{
public int Id { get; private set; }
public string Code { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
B. DAL.interfaces.dll 或 Common.dll 中定义了 Query、IRepository 和 IUnitOfWork 的类(但不包括在 DAL 中!)。
public class Query
{
public string Text { get; set; }
}
public interface IRepository<TEntity>
where TEntity : class
{
bool TryGet(int key, out TEntity value);
TEntity this[int key] { get; }
IEnumerable<TEntity> GetAll();
bool TryGetFirst(Query condition, out TEntity value);
TEntity GetFirst(Query condition);
IEnumerable<TEntity> GetAll(Query condition);
int Count { get; }
}
public interface IUnitOfWork
{
void SetAdded(TEntity value);
void SetRemoved(TEntity value);
void SetChanged(TEntity value);
void Save();
}
IUnitOfWork 能够感知变更的实体。 Save() 方法会针对每个变更的实体调用相应的 DatabaseHelper / OdbcHelper CRUD 方法,以将更改持久化到数据库。
IRepository<Product>, ... IRepository<EntityXY> 和 IUnitOFWork 的实现应放在 DAL 中。然后 BLL 使用 IRepository 和 IUnitOFWork 来实现业务(领域)逻辑。BLL 本身可以作为 服务层 组织在领域模型之上,但这超出了本讨论的范围 :).
希望我的回答有所帮助。
如果您有任何问题,请随时问我...
链接:
Martin Fowler 的企业应用架构模式