一、依赖注入方式
1.1 安装两个依赖包 <PackageReference Include="Mapster.DependencyInjection" Version="1.0.0" /> <PackageReference Include="Mapster" Version="7.2.0" />
1.2 配置映射关系 public class InitMapsterAdaptConifg { public TypeAdapterConfig InitMapperConfig() { TypeAdapterConfig config = new TypeAdapterConfig(); config.ForType<School, SchoolDisplayDto>() .Map(s => s.SchoolId, d => d.Id) .Map(s => s.SchoolIdName, d => d.Id + d.Name) .Map(d => d.SchoolName, s => s.Name) .IgnoreNullValues(true); return config; } }
1.3 Startup 中注入服务 TypeAdapterConfig 必须Singleton 单例注入 public void ConfigureServices(IServiceCollection services) { services.AddSingleton(new InitMapsterAdaptConifg().InitMapperConfig()); services.AddScoped<IMapper, ServiceMapper>(); }
1.4 在服务中注入 调用 private readonly IMapper _mapper; public SchoolAppService(ISqlSugarClient context = null, IMapper mapper = null) : base(context) { base.Context = context; _mapper = mapper; } public async Task<PagedOutput<SchoolDisplayDto>> GetSchoolPage(SchoolPagedInput input) { PagedOutput<SchoolDisplayDto> output = new PagedOutput<SchoolDisplayDto>(); RefAsync<int> total = 0; var query = Context.Queryable<School>() .WhereIF(!string.IsNullOrWhiteSpace(input.Name), x => x.Name.Contains(input.Name)); output.TotalCount = await query.CountAsync(); var scList = await query .OrderBy(x => x.Id, OrderByType.Desc) .ToPageListAsync(input.PageIndex, input.PageSize, total); output.TotalCount = total.Value; output.Data = _mapper.Map<IEnumerable<School>, IEnumerable<SchoolDisplayDto>>(scList); return output; }