using System.Threading.Tasks; using Util.Applications; using Util.Datas.Sql; using Util.Domains.Repositories; using Util.Exceptions; using Util.Maps; using Util.Samples.Data; using Util.Samples.Domain.Models; using Util.Samples.Domain.Repositories; using Util.Samples.Service.Abstractions.Systems; using Util.Samples.Service.Dtos.Systems; using Util.Samples.Service.Queries.Systems; namespace Util.Samples.Service.Implements.Systems { /// /// 应用程序服务 /// public class ApplicationService : CrudServiceBase, IApplicationService { /// /// 初始化应用程序服务 /// /// 工作单元 /// 应用程序仓储 /// Sql查询对象 public ApplicationService( ISampleUnitOfWork unitOfWork, IApplicationRepository applicationRepository, ISqlQuery sqlQuery ) : base( unitOfWork, applicationRepository ) { ApplicationRepository = applicationRepository; SqlQuery = sqlQuery; } /// /// 应用程序仓储 /// public IApplicationRepository ApplicationRepository { get; set; } /// /// Sql查询对象 /// public ISqlQuery SqlQuery { get; } /// /// 转换为数据传输对象 /// /// 实体 protected override ApplicationDto ToDto( Application entity ) { if( entity == null ) return new ApplicationDto(); return entity.MapTo(); } /// /// 转换为实体 /// /// 数据传输对象 protected override Application ToEntity( ApplicationDto dto ) { if( dto == null ) return new Application(); return dto.MapTo( new Application( dto.Id.ToGuid() ) ); } /// /// 分页查询 /// /// 查询参数 public override async Task> PagerQueryAsync( ApplicationQuery query ) { return await SqlQuery .Select( true ) .From( "a" ) .WhereIfNotEmpty( t => t.Code.Contains( query.Code ) ) .WhereIfNotEmpty( t => t.Name.Contains( query.Name ) ) .WhereIfNotEmpty( t => t.Comment.Contains( query.Comment ) ) .OrIfNotEmpty( t => t.Code.Contains( query.Keyword ), t => t.Name.Contains( query.Keyword ) ) .ToPagerListAsync( query ); } /// /// 创建前操作 /// protected override async Task CreateBeforeAsync( Application entity ) { await base.CreateBeforeAsync( entity ); if( await ApplicationRepository.ExistsAsync( t => t.Code == entity.Code ) ) ThrowCodeRepeatException( entity.Code ); if( await ApplicationRepository.ExistsAsync( t => t.Name == entity.Name ) ) ThrowNameRepeatException( entity.Name ); } /// /// 抛出编码重复异常 /// private void ThrowCodeRepeatException( string code ) { throw new Warning( $"应用程序编码 {code} 已存在" ); } /// /// 抛出名称重复异常 /// private void ThrowNameRepeatException( string name ) { throw new Warning( $"应用程序名称 {name} 已存在" ); } /// /// 修改前操作 /// protected override async Task UpdateBeforeAsync( Application entity ) { await base.UpdateBeforeAsync( entity ); if( await ApplicationRepository.ExistsAsync( t => t.Id != entity.Id && t.Code == entity.Code ) ) ThrowCodeRepeatException( entity.Code ); if( await ApplicationRepository.ExistsAsync( t => t.Id != entity.Id && t.Name == entity.Name ) ) ThrowNameRepeatException( entity.Name ); } } }