文章目录
一、前言
项目中通常习惯性的针对每一个实体在应用层创建继承自现有的CrudAppService服务,来获得标配的增删改查接口功能,但有的时候需要用自定义仓储服务来个性化的数据操作需求;
如:我们需要在商品Goods表中牛奶Index=2后面插入一条香蕉记录Index=3,所有商品记录通过Index字段由大到小排序,这时候需要先将比牛奶Index=2大的所有记录Index+1,然后插入Index=2+1的香蕉记录;
这时候就可以为Goods商品添加自定义仓储事件来实现在把指定某件Id商品 后的所有Index+1,然后按正常操作新增记录;
二、自定义仓储步骤
1、在Domain领域层添加自定义仓储接口申明
//IPresetCruise_PointsRepository.cs
public interface IPresetCruise_PointsRepository : IRepository<PresetCruise_Points, int>
{
Task IndexIncreaseAfterIdAsync(int id);
}
2、在EntityFrameworkCore基础设施层实现接口服务
/// <summary>
/// 预置点自定义仓储类
/// </summary>
public class PresetCruise_PointsRepository : EfCoreRepository<GasMonitoringDbContext, PresetCruise_Points, int>, IPresetCruise_PointsRepository
{
public PresetCruise_PointsRepository(IDbContextProvider<GasMonitoringDbContext> dbContextProvider) : base(dbContextProvider)
{
}
/// <summary>
/// 自动批量+1
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public async Task IndexIncreaseAfterIdAsync(int id)
{
var tmpEntity = this.DbContext.PresetCruise_Points.FirstOrDefault(p => p.Id == id);
if (tmpEntity == null)
{
return;
}
//把后面所有记录Index批量+1 ,注意这地方使用了Z.EntityFramework.Plus开源组件
await this.DbContext.PresetCruise_Points.Where(p => p.Index > tmpEntity.Index)
.UpdateAsync(p => new PresetCruise_Points() { Index = p.Index + 1 });
}
}
3、在Application应用层 注入并使用服务
public class PresetCruise_PointAppService : CrudAppService<PresetCruise_Points, PresetCruisePointDto, int, PagedResultRequestDto, CreatePresetCruisePointDto, PresetCruisePointDto>, IPresetCruise_PointAppService
{
/// <summary>
/// 构造函数注入预置点位自定义仓储
/// </summary>
private readonly IPresetCruise_PointsRepository _presetCruise_PointsRepository;
public PresetCruise_PointAppService(IRepository<PresetCruise_Points, int> repository, IPresetCruise_PointsRepository presetCruise_PointsRepository) : base(repository)
{
_presetCruise_PointsRepository = presetCruise_PointsRepository;
}
/// <summary>
/// 比自定记录Id大的所有记录 对应的排序Index +1
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public async Task IndexIncreaseAfterIdAsync(int id)
{
await _presetCruise_PointsRepository.IndexIncreaseAfterIdAsync(id);
}
}
三、总结
这里只是单纯演示了自定义仓储的实现过程,至于什么内容应该放在仓储服务中,什么内容应该放在领域服务中,什么内容应该放在应用层服务中 是个来回拉锯的问题,有一定的标准,也看个人如何理解;
下一节讲解如何批量操作表记录;