有时候实际业务中主键不一定叫Id,比如示例数据库Northwind中的RegionID,TerritoryID等,本示例用Abp框架并以Northwind数据库Region表为数据依据
一、在Core领域层创建Region实体
using System.ComponentModel.DataAnnotations.Schema; using Abp.Domain.Entities; namespace Blogs.Northwind { public class Region : Entity<int> { //定义数据库中实际列名 [Column("RegionId")] //重写RegionId主键为ID public override int Id { get; set; } public string RegionDescription { get; set; } } }
二、DbContext增加DbSet属性
public DbSet<Region> Region { get; set; }
三、Application层创建Dto
using Abp.Application.Services.Dto; namespace Blogs.Northwind.Regions.Dto { public class RegionDto : EntityDto<int> { public string RegionDescription { get; set; } } }
四、创建RegionProfile并继承Profile,作为AutoMapper映射配置
using AutoMapper; namespace Blogs.Northwind.Regions.Dto { public class RegionProfile : Profile { public RegionProfile() { CreateMap<Region, RegionDto>(); // } } }
五、创建IRegionAppService接口服务
using System.Threading.Tasks; using Abp.Application.Services; using Abp.Application.Services.Dto; using Blogs.Northwind.Regions.Dto; namespace Blogs.Northwind.Regions { public interface IRegionAppService : IApplicationService { Task<ListResultDto<RegionDto>> GetAllAsync(); } }
六、实现RegionAppService
using System.Collections.Generic; using System.Threading.Tasks; using Abp.Application.Services.Dto; using Abp.Domain.Repositories; using Blogs.Northwind.Regions.Dto; namespace Blogs.Northwind.Regions { public class RegionAppService : BlogsAppServiceBase, IRegionAppService { private readonly IRepository<Region> _repository; public RegionAppService(IRepository<Region> repository) { _repository = repository; } public async Task<ListResultDto<RegionDto>> GetAllAsync() { var result = await _repository.GetAllListAsync(); //result为List<Region>类型 var model = ObjectMapper.Map<List<RegionDto>>(result); //ObjectMapper<目标>(源),把result(List<region>)转为List<RegionDto>类型 return new ListResultDto<RegionDto>(model); } } }
七、测试结果达到预期
八、补充:显示结果为Id,正常应该为RegionId,需要做以下修改
//RegionDto
namespace Blogs.Northwind.Regions.Dto { public class RegionDto //取消继承EntityDto<T>继承后会自动添加<T>类型为Id的主键 { public int RegionID { get; set; } public string RegionDescription { get; set; } } }
//RegionProfile using AutoMapper; namespace Blogs.Northwind.Regions.Dto { public class RegionProfile : Profile { public RegionProfile() {
//创建映射配置CreateMap<源类型,转换后类型>().ForMember(转换后属性,从哪里转换)个人理解,把RegionDto Id属性作为映射条件转为Region RegionId属性 CreateMap<Region, RegionDto>().ForMember(dest=> dest.RegionID,opt=>opt.MapFrom(x=>x.Id)); } } }
执行结果如下,达到预期效果