AutoMapper 实体间的相互转换 对象-对象映射器
在startup 中注册 一下让全局生效
{ services.AddAutoMapper(options => { options.AddProfile<AutoMapConfig>(); }); }
在 AutoMapConfig 中配置映射规则
public class AutoMapConfig : Profile { //映射规则 public AutoMapConfig() { CreateMap<PageResult<Commodity>, PagingData<CommodityDTO>>() // 来源实体 目标实体 .ForMember(c => c.PageIndex, s => s.MapFrom(c => c.PageIndex)) // 目标字段 来自字段 .ForMember(c => c.PageSize, s => s.MapFrom(c => c.PageSize)) .ForMember(c => c.RecordCount, s => s.MapFrom(c => c.TotalCount)) .ForMember(c => c.DataList, s => s.MapFrom(c => c.DataList)) .ReverseMap(); //这句是支持相互转换的. //如果属性名称相同其实是可以不用写,如果写了也更好 CreateMap<Commodity, CommodityDTO>() .ForMember(c => c.Id, s => s.MapFrom(c => c.Id)) .ForMember(c => c.ImageUrl, s => s.MapFrom(c => c.ImageUrl)) .ForMember(c => c.Price, s => s.MapFrom(c => c.Price)) .ForMember(c => c.ProductId, s => s.MapFrom(c => c.ProductId)) .ForMember(c => c.Title, s => s.MapFrom(c => c.Title)) .ForMember(c => c.Url, s => s.MapFrom(c => c.Url)) .ForMember(c => c.CategoryId, s => s.MapFrom(c => c.CategoryId)); } }
使用
private IMapper _IMapper = null; this._IMapper = mapper; //注入进来 PagingData<CommodityDTO> model = _IMapper.Map<PageResult<Commodity>, PagingData<CommodityDTO>>(data);
实体
public class PageResult<T> { public int TotalCount { get; set; } public int PageIndex { get; set; } public int PageSize { get; set; } public List<T> DataList { get; set; } } public class PagingData<T> where T : class { public int RecordCount { get; set; } public int PageIndex { get; set; } public int PageSize { get; set; } public List<T> DataList { get; set; } public string SearchString { get; set; } } public partial class Commodity { public int Id { get; set; } public long? ProductId { get; set; } public int? CategoryId { get; set; } public string Title { get; set; } public decimal? Price { get; set; } public string Url { get; set; } public string ImageUrl { get; set; } } public class CommodityDTO { public int Id { get; set; } public long? ProductId { get; set; } public int? CategoryId { get; set; } [Required(ErrorMessage = "Title不能为空")] [StringLength(500,ErrorMessage ="最长只能是500长度")] public string Title { get; set; } public decimal? Price { get; set; } [Required(ErrorMessage = "Url不能为空")] [StringLength(1000)] public string Url { get; set; } [StringLength(1000)] public string ImageUrl { get; set; } }
浙公网安备 33010602011771号