在依赖项中右击打开管理Nuget程序包,搜索AutoMapper并安装。
使用AutoMapper将一个对象赋值给另外一个对象
BookDto 实体类对象
public class BookDto { public string Title { get; set; } public string Author { get; set; } public int Status { get; set; } public int buyCount { get; set; } = 5; public DateTime CreateDate { get; set; } = DateTime.Now; public string Remark { get; set; } = "123456789765432"; public string Test1 { get; set; } }
BookViewModel 用户显示视图的模型对象
public class BookViewModel { public string Title { get; set; } public string Author { get; set; } public string StatusText { get; set; } public string CreateDate { get; set; } public int buyCount { get; set; } public string Remark { get; set; } public string Test1 { get; set; } public string BookInfo { get; set; } }
得到BookDto的实例对象,需要给BookViewModel
BookDto book = new BookDto() { Author = "度边", Title = "知行合一王阳明", Status = 1 };
如何将BookDto实例对象的值赋给BookViewModel实例呢?
/// <summary> /// 使用AutoMaper将BookDto实例赋值给BookViewModel实例 /// </summary> /// <param name="book"></param> /// <returns></returns> public static BookViewModel PrepareBookViewModel(BookDto book) { var config2 = new MapperConfiguration( cfg => cfg.CreateMap<BookDto, BookViewModel>() .ForMember(d => d.Title, opt => opt.MapFrom(s => s.Title)) //指定字段一一对应 .ForMember(d => d.CreateDate, opt => opt.MapFrom(src => src.CreateDate.ToString("yy-MM-dd HH:mm:ss")))//指定字段,并转化指定的格式 .ForMember(d => d.buyCount, opt => opt.Condition(src => src.buyCount > 5))//条件赋值 .ForMember(d => d.Remark, opt => opt.Ignore())//忽略该字段,不给该字段赋值 .ForMember(d => d.Test1, opt => opt.NullSubstitute("空了"))//如果源字段值为空,则赋值为 空了 .ForMember(d => d.StatusText, opt => { opt.MapFrom(s => s.Status == 1 ? "可用" : "不可用"); }) .ForMember(d => d.BookInfo, opt => opt.MapFrom(src => src.Title + src.CreateDate.ToString("yyyy-MM-dd"))));//可以自己随意组合赋值 var mapper2 = config2.CreateMapper(); return mapper2.Map<BookViewModel>(book); }