C#实现对象映射AutoMapper
Posted Besos
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C#实现对象映射AutoMapper相关的知识,希望对你有一定的参考价值。
1.引用AutoMapper包
2.定义两个实体类
public class ModelA { public string UserId { get; set; } public string Remark { get; set; } } public class ModelB { public string User_id { get; set; } public string Remark_msg { get; set; } public int Lab_id { get; set; } }
3.定义映射规则,并映射
public List<ModelB> MappingModeB(List<ModelA> data, int lab_Id) { MapperConfiguration config = new MapperConfiguration ( mp => mp.CreateMap<ModelA, ModelB>() // 给config进行配置映射规则 .ForMember(nclog => nclog.User_id, clog => clog.MapFrom(log => log.UserId == null ? "" : log.UserId)) // 指定映射字段 .ForMember(nclog => nclog.Remark_msg, clog => clog.MapFrom(log => log.Remark)) .ForMember(nclog => nclog.Lab_id, clog => clog.MapFrom(log => lab_Id)) ); var Modellogs = config.CreateMapper(); return Modellogs.Map<List<ModelB>>(data); //映射 }
以上是关于C#实现对象映射AutoMapper的主要内容,如果未能解决你的问题,请参考以下文章