一,如下例子:
using AutoMapper; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AutoMapper2 { class Program { static void Main(string[] args) { //实体属性完全一致映射 Test.InitAutoMapper<ProductDto, Product>(); ProductDto userDto = new ProductDto() { Name = "实体映射", Num = 20, }; //实体间的映射不区分大小写 var o = Mapper.Map<ProductDto, Product>(userDto); var t = Mapper.Map<Product, ProductDto3>(o); //当属性命名大小写不一致时 Test.InitAutoMapper<ProductDto3, Product>(); ProductDto3 userDto3 = new ProductDto3() { Id = 1, Name = "实体映射", Num = 20, Price = 1 }; //实体间的映射不区分大小写 var oDomain = Mapper.Map<ProductDto3, Product>(userDto3); var te = Mapper.Map<Product, ProductDto3>(oDomain); //有DTO模式到聚合根的转换 ProductDto2 userDto2 = new ProductDto2() { Name2 = "实体映射", Num2 = 20, Address = "XXX" }; var map = Mapper.CreateMap<ProductDto2, Product>() .ForMember(d => d.Name, opt => opt.MapFrom(x => x.Name2)) .ForMember(d => d.adress.Name, opt => opt.MapFrom(x => x.Address)); var tt = Mapper.Map<ProductDto2, Product>(userDto2); } } public class Test { public static void InitAutoMapper<DtoModel, DomainModel>() { var oType = Mapper.FindTypeMapFor<DtoModel, DomainModel>(); if (oType == null) { Mapper.CreateMap<DtoModel, DomainModel>(); Mapper.CreateMap<DomainModel, DtoModel>(); } } } public class Product { public int Id { get; set; } public string Name { get; set; } public int Num { get; set; } public int Price { get; set; } public Adress adress { get; set; } } public class Adress { public string Name { get; set; } } public class ProductDto { public string Name { get; set; } public int Num { get; set; } } public class ProductDto2 { public string Name2 { get; set; } public int Num2 { get; set; } public string Address { get; set; } } public class ProductDto3 { public int Id { get; set; } public string Name { get; set; } public int Num { get; set; } public int Price { get; set; } } }