在 ABP 中, 仓储类要实现 IRepository 接口, 接口定义了常用的增删改查以及聚合方法, 其中包括同步及异步方法主要包括以下方法:
仓储(Repository): 仓储用来操作数据库进行数据存取仓储接口在领域层定义, 而仓储的实现类应该写在基础设施层
在 ABP 中, 仓储类要实现 IRepository 接口, 接口定义了常用的增删改查以及聚合方法, 其中包括同步及异步方法主要包括以下方法:
针对 NHibernate, 提供了 NhRepositoryBase 的泛型版本的实现方式
泛型版本的实现就意味着, 大多数的时候, 这些方法已足已应付一般实体的需要如果这些方法对于实体来说已足够, 我们便不需要再去创建这个实体所需的仓储接口 / 类
直接通过在应用服务层定义仓储引用, 然后通过构造函数注入即可在我们的应用服务层即可按以下方式使用 Task 仓储:
- public class TaskAppService : ITaskAppService {
- private readonly IRepository _taskRepository;
- public TaskAppService(IRepository taskRepository)
- {
- _taskRepository = taskRepository;
- }
示例代码中使用的就是这种方式
二如何实现自定义仓储
假设我们需要查找某个用户都分配哪些任务
在领域层, 创建 IRepositories 文件夹, 然后定义 IBackendTaskRepository
- namespace LearningMpaAbp.IRepositories
- {///
- /// 自定义仓储示例 ///
- public interface IBackendTaskRepository : IRepository
- { ///
- /// 获取某个用户分配了哪些任务
- ///
- /// 用户 Id
- /// 任务列表
- List GetTaskByAssignedPersonId(long personId);
- }
- }
在基础架构层, 实现该仓储
- namespace LearningMpaAbp.EntityFramework.Repositories
- {public class BackendTaskRepository:LearningMpaAbpRepositoryBase,IBackendTaskRepository{
- public BackendTaskRepository(IDbContextProvider dbContextProvider) : base(dbContextProvider)
- {
- } ///
- /// 获取某个用户分配了哪些任务
- ///
- /// 用户 Id
- /// 任务列表
- public List GetTaskByAssignedPersonId(long personId)
- { var query = GetAll(); if (personId>0)
- {
- query = query.Where(t => t.AssignedPersonId == personId);
- } return query.ToList();
- }
- }
- }
该仓储实现, 继承自模板生成的 LearningMpaAbpRepositoryBase 泛型抽象类, 然后再实现 IBackendTaskRepository 接口这里要显示声明实现类的有参构造函数, 使用泛型的 IDbContextProvider 将数据库上下文的子类 ChargeStationContext 传给父类的构造函数
来源: https://www.php1.cn/detail/php-141c7946d1.html