• c# automapper 使用


    一、最简单的用法

    有两个类User和UserDto

    复制代码
     1     public class User
     2     {
     3         public int Id { get; set; }
     4         public string Name { get; set; }
     5         public int Age { get; set; }
     6     }
     7 
     8     public class UserDto
     9     {
    10         public string Name { get; set; }
    11         public int Age { get; set; }
    12     }
    复制代码

    将User转换成UserDto也和简单

    复制代码
    1     Mapper.Initialize(x => x.CreateMap<User, UserDto>());
    2     User user = new User()
    3     {
    4         Id = 1,
    5         Name = "caoyc",
    6         Age = 20
    7     };
    8     var dto = Mapper.Map<UserDto>(user);
    复制代码

     这是一种最简单的使用,AutoMapper会更加字段名称去自动对于,忽略大小写。

    二、如果属性名称不同

    将UserDto的Name属性改成Name2

    复制代码
     1     Mapper.Initialize(x => 
     2         x.CreateMap<User, UserDto>()
     3          .ForMember(d =>d.Name2, opt => {
     4             opt.MapFrom(s => s.Name);
     5             })
     6         );
     7 
     8     User user = new User()
     9     {
    10         Id = 1,
    11         Name = "caoyc",
    12         Age = 20
    13     };
    14 
    15     var dto = Mapper.Map<UserDto>(user);
    复制代码

    三、使用Profile配置

    自定义一个UserProfile类继承Profile,并重写Configure方法

    复制代码
     1     public class UserProfile : Profile
     2     {
     3         protected override void Configure()
     4         {
     5             CreateMap<User, UserDto>()
     6                 .ForMember(d => d.Name2, opt =>
     7                 {
     8                     opt.MapFrom(s => s.Name);
     9                 });
    10         }
    11     }
    复制代码

    使用时就这样

    复制代码
     1     Mapper.Initialize(x => x.AddProfile<UserProfile>());
     2 
     3     User user = new User()
     4     {
     5         Id = 1,
     6         Name = "caoyc",
     7         Age = 20
     8     };
     9 
    10     var dto = Mapper.Map<UserDto>(user);
    复制代码

    四、空值替换NullSubstitute

    空值替换允许我们将Source对象中的空值在转换为Destination的值的时候,使用指定的值来替换空值。

    复制代码
     1     public class UserProfile : Profile
     2     {
     3         protected override void Configure()
     4         {
     5             CreateMap<User, UserDto>()
     6                 .ForMember(d => d.Name2, opt => opt.MapFrom(s => s.Name))
     7                 .ForMember(d => d.Name2, opt => opt.NullSubstitute("值为空"));
     8                 
     9         }
    10     }
    复制代码
    复制代码
    1     Mapper.Initialize(x => x.AddProfile<UserProfile>());
    2 
    3     User user = new User()
    4     {
    5         Id = 1,
    6         Age = 20
    7     };
    8 
    9     var dto = Mapper.Map<UserDto>(user);
    复制代码

    结果为:

    五、忽略属性Ignore

    复制代码
     1     public class User
     2     {
     3         public int Id { get; set; }
     4         public string Name { get; set; }
     5         public int Age { get; set; }
     6     }
     7 
     8     public class UserDto
     9     {
    10         public string Name { get; set; }
    11         public int Age { get; set; }
    12 
    13     }
    14 
    15     public class UserProfile : Profile
    16     {
    17         protected override void Configure()
    18         {
    19             CreateMap<User, UserDto>().ForMember("Name", opt => opt.Ignore());
    20         }
    21     }
    复制代码

    使用

    复制代码
     1     Mapper.Initialize(x => x.AddProfile<UserProfile>());
     2 
     3     User user = new User()
     4     {
     5         Id = 1,
     6         Name="caoyc",
     7         Age = 20
     8     };
     9 
    10     var dto = Mapper.Map<UserDto>(user);
    复制代码

    结果:

    六、预设值

    如果目标属性多于源属性,可以进行预设值

    复制代码
     1     public class User
     2     {
     3         public int Id { get; set; }
     4         public string Name { get; set; }
     5         public int Age { get; set; }
     6     }
     7 
     8     public class UserDto
     9     {
    10         public string Name { get; set; }
    11         public int Age { get; set; }
    12         public string Gender { get; set; }
    13 
    14     }
    15 
    16     public class UserProfile : Profile
    17     {
    18         protected override void Configure()
    19         {
    20             CreateMap<User, UserDto>();
    21         }
    22     }
    复制代码

    使用

    复制代码
     1     Mapper.Initialize(x => x.AddProfile<UserProfile>());
     2 
     3     User user = new User()
     4     {
     5         Id = 1,
     6         Name="caoyc",
     7         Age = 20
     8     };
     9 
    10     UserDto dto = new UserDto() {Gender = "男"};
    11     Mapper.Map(user, dto);
    复制代码

     七、类型转换ITypeConverter

    如果数据中Gender存储的int类型,而DTO中Gender是String类型

    复制代码
    1     public class User
    2     {
    3         public int Gender { get; set; }
    4     }
    5 
    6     public class UserDto
    7     {
    8         public string Gender { get; set; }
    9     }
    复制代码

    类型转换类,需要实现接口ITypeConverter

    复制代码
     1     public class GenderTypeConvertert : ITypeConverter<int, string>
     2     {
     3         public string Convert(int source, string destination, ResolutionContext context)
     4         {
     5             switch (source)
     6             {
     7                 case 0:
     8                     destination = "男";
     9                     break;
    10                 case 1:
    11                     destination = "女";
    12                     break;
    13                 default:
    14                     destination = "未知";
    15                     break;
    16             }
    17             return destination;
    18         }
    19     }
    复制代码

    配置规则

    复制代码
     1     public class UserProfile : Profile
     2     {
     3         protected override void Configure()
     4         {
     5             CreateMap<User, UserDto>();
     6 
     7             CreateMap<int, string>().ConvertUsing<GenderTypeConvertert>();
     8             //也可以写这样
     9             //CreateMap<int, string>().ConvertUsing(new GenderTypeConvertert());
    10         }
    11     }
    复制代码

    使用

    复制代码
     1     Mapper.Initialize(x => x.AddProfile<UserProfile>());
     2 
     3     User user0 = new User() { Gender = 0 };
     4     User user1 = new User() { Gender = 1 };
     5     User user2 = new User() { Gender = 2 };
     6     var dto0= Mapper.Map<UserDto>(user0);
     7     var dto1 = Mapper.Map<UserDto>(user1);
     8     var dto2 = Mapper.Map<UserDto>(user2);
     9 
    10     Console.WriteLine("dto0:{0}", dto0.Gender);
    11     Console.WriteLine("dto1:{0}", dto1.Gender);
    12     Console.WriteLine("dto2:{0}", dto2.Gender);
    复制代码

    结果

    八、条件约束Condition

    当满足条件时才进行映射字段,例如人类年龄,假设我们现在人类年龄范围为0-200岁(这只是假设),只有满足在这个条件才进行映射

    DTO和Entity

    复制代码
    1     public class User
    2     {
    3         public int Age { get; set; }
    4     }
    5 
    6     public class UserDto
    7     {
    8         public int Age { get; set; }
    9     }
    复制代码

    Profile

    复制代码
    1     public class UserProfile : Profile
    2     {
    3         protected override void Configure()
    4         {
    5             CreateMap<User, UserDto>().ForMember(dest=>dest.Age,opt=>opt.Condition(src=>src.Age>=0 && src.Age<=200));
    6         }
    7     }
    复制代码

    使用代码

    复制代码
     1     Mapper.Initialize(x => x.AddProfile<UserProfile>());
     2 
     3     User user0 = new User() { Age = 1 };
     4     User user1 = new User() { Age = 150 };
     5     User user2 = new User() { Age = 201 };
     6     var dto0= Mapper.Map<UserDto>(user0);
     7     var dto1 = Mapper.Map<UserDto>(user1);
     8     var dto2 = Mapper.Map<UserDto>(user2);
     9 
    10     Console.WriteLine("dto0:{0}", dto0.Age);
    11     Console.WriteLine("dto1:{0}", dto1.Age);
    12     Console.WriteLine("dto2:{0}", dto2.Age);
    复制代码

    输出结果

    using System;  
    using System.Collections.Generic;  
    using System.Linq;  
    using System.Text;  
    using System.Threading.Tasks;  
    using AutoMapper;  
    using System.Data;  
      
    namespace ConsoleApplication2  
    {  
        class Program  
        {  
      
            static void Main(string[] args)  
            {  
                //1.普通转换  
                Name name1 = new Name() { FirstName = "L", LastName = "jz" };  
                Mapper.CreateMap<Name, NameDto>()  
                .BeforeMap((name, nameDto) => Console.WriteLine("hello world before"))  
                .AfterMap((name, nameDto) => Console.WriteLine("hello world after"));  
                NameDto nameDto1 = Mapper.Map<Name, NameDto>(name1);  
                Console.WriteLine("1");  
                Console.WriteLine(nameDto1.FirstName + nameDto1.LastName);  
                Console.WriteLine();  
                //Console.ReadKey();  
      
                //整体设置  
                //2.整体即时转换  
                Mapper.Reset();  
                Name name2 = new Name() { FirstName = "L", LastName = "jz" };  
                Mapper.CreateMap<Name, NameDto>()  
                .ConstructUsing(name => new NameDto() { AllName = name.FirstName + name.LastName });  
                NameDto nameDto2 = Mapper.Map<Name, NameDto>(name2);  
                Console.WriteLine("2");  
                Console.WriteLine(nameDto2.AllName);  
                Console.WriteLine();  
                //Console.ReadKey();  
      
                //3.整体通过TypeConverter类型转换  
                Mapper.Reset();  
                Name name3 = new Name() { FirstName = "L", LastName = "jz" };  
                Mapper.CreateMap<Name, NameDto>()  
                .ConvertUsing<NameConverter>();  
                NameDto nameDto3 = Mapper.Map<Name, NameDto>(name3);  
                Console.WriteLine("3");  
                Console.WriteLine(nameDto3.AllName);  
                Console.WriteLine();  
                //Console.ReadKey();  
      
                //单属性设置  
                //4.属性条件转换  
                Mapper.Reset();  
                Name name4 = new Name() { FirstName = "L", LastName = "jz" };  
                Mapper.CreateMap<Name, NameDto>()  
                .ForMember(name => name.FirstName, opt => opt.Condition(name => !name.FirstName.Equals("l", StringComparison.OrdinalIgnoreCase)));  
                NameDto nameDto4 = Mapper.Map<Name, NameDto>(name4);  
                Console.WriteLine("4");  
                Console.WriteLine(string.IsNullOrEmpty(nameDto4.FirstName));  
                Console.WriteLine();  
                //Console.ReadKey();  
      
                //5.属性忽略  
                Mapper.Reset();  
                Name name5 = new Name() { FirstName = "L", LastName = "jz" };  
                Mapper.CreateMap<Name, NameDto>()  
                .ForMember(name => name.FirstName, opt => opt.Ignore());  
                NameDto nameDto5 = Mapper.Map<Name, NameDto>(name5);  
                Console.WriteLine("5");  
                Console.WriteLine(string.IsNullOrEmpty(nameDto5.FirstName));  
                Console.WriteLine();  
                //Console.ReadKey();  
      
                //6.属性转换  
                Mapper.Reset();  
                Name name6 = new Name() { FirstName = "L", LastName = "jz" };  
                Mapper.CreateMap<Name, NameDto>()  
                .ForMember(name => name.AllName, opt => opt.MapFrom(name => name.FirstName + name.LastName))  
                .ForMember(name => name.FirstName, opt => opt.MapFrom(name=>name.FirstName));  
                NameDto nameDto6 = Mapper.Map<Name, NameDto>(name6);  
                Console.WriteLine("6");  
                Console.WriteLine(nameDto6.AllName);  
                Console.WriteLine();  
                //Console.ReadKey();  
      
                //7.属性通过ValueResolver转换  
                Mapper.Reset();  
                Name name7 = new Name() { FirstName = "L", LastName = "jz" };  
                Mapper.CreateMap<Name, StoreDto>()  
                .ForMember(storeDto => storeDto.Name, opt => opt.ResolveUsing<NameResolver>());  
                StoreDto store1 = Mapper.Map<Name, StoreDto>(name7);  
                Console.WriteLine("7");  
                Console.WriteLine(store1.Name.FirstName + store1.Name.LastName);  
                Console.WriteLine();  
                //Console.ReadKey();  
      
                //8.属性填充固定值  
                Mapper.Reset();  
                Name name8 = new Name() { FirstName = "L", LastName = "jz" };  
                Mapper.CreateMap<Name, NameDto>()  
                .ForMember(name => name.AllName, opt => opt.UseValue<string>("ljzforever"));  
                NameDto nameDto8 = Mapper.Map<Name, NameDto>(name8);  
                Console.WriteLine("8");  
                Console.WriteLine(nameDto8.AllName);  
                Console.WriteLine();  
                //Console.ReadKey();  
      
                //9.属性格式化  
                Mapper.Reset();  
                Name name9 = new Name() { FirstName = "L", LastName = "jz" };  
                Mapper.CreateMap<Name, NameDto>()  
                .ForMember(name => name.FirstName, opt => opt.AddFormatter<StringFormatter>());  
                NameDto nameDto9 = Mapper.Map<Name, NameDto>(name9);  
                Console.WriteLine("9");  
                Console.WriteLine(nameDto9.FirstName);  
                Console.WriteLine();  
                //Console.ReadKey();  
      
                //10.属性null时的默认值  
                Mapper.Reset();  
                Name name10 = new Name() { FirstName = "L" };  
                Mapper.CreateMap<Name, NameDto>()  
                .ForMember(name => name.LastName, opt => opt.NullSubstitute("jz"));  
                NameDto nameDto10 = Mapper.Map<Name, NameDto>(name10);  
                Console.WriteLine("10");  
                Console.WriteLine(nameDto10.LastName);  
                Console.WriteLine();  
                //Console.ReadKey();  
      
                //其它设置与特性  
                //11.转换匿名对象  
                Mapper.Reset();  
                object name11 = new { FirstName = "L", LastName = "jz" };  
                NameDto nameDto11 = Mapper.DynamicMap<NameDto>(name11);  
                Console.WriteLine("11");  
                Console.WriteLine(nameDto11.FirstName + nameDto11.LastName);  
                Console.WriteLine();  
                //Console.ReadKey();  
      
                //12.转换DataTable  
                Mapper.Reset();  
                DataTable dt = new DataTable();  
                dt.Columns.Add("FirstName", typeof(string));  
                dt.Columns.Add("LastName", typeof(string));  
                dt.Rows.Add("L", "jz");  
                List<NameDto> nameDto12 = Mapper.DynamicMap<IDataReader, List<NameDto>>(dt.CreateDataReader());  
                Console.WriteLine("12");  
                Console.WriteLine(nameDto12[0].FirstName + nameDto12[0].LastName);  
                Console.WriteLine();  
                //Console.ReadKey();  
                //emitMapper error  
                //List<NameDto> nameDto20 = EmitMapper.ObjectMapperManager.DefaultInstance.GetMapper<IDataReader, List<NameDto>>().Map(dt.CreateDataReader());  
      
      
                //13.转化存在的对象  
                Mapper.Reset();  
                Mapper.CreateMap<Name, NameDto>()  
                .ForMember(name => name.LastName, opt => opt.Ignore());  
                Name name13 = new Name() { FirstName = "L" };  
                NameDto nameDto13 = new NameDto() { LastName = "jz" };  
                Mapper.Map<Name, NameDto>(name13, nameDto13);  
                //nameDto13 = Mapper.Map<Name, NameDto>(name13);//注意,必需使用上面的写法,不然nameDto13对象的LastName属性会被覆盖  
                Console.WriteLine("13");  
                Console.WriteLine(nameDto13.FirstName + nameDto13.LastName);  
                Console.WriteLine();  
                //Console.ReadKey();  
      
                //14.Flatten特性 Store.Name.FirtName=FlattenName.NameFirstname  
                Mapper.Reset();  
                Mapper.CreateMap<Store, FlattenName>();  
                Store store2 = new Store() { Name = new Name() { FirstName = "L", LastName = "jz" } };  
                FlattenName nameDto14 = Mapper.Map<Store, FlattenName>(store2);  
                Console.WriteLine("14");  
                Console.WriteLine(nameDto14.NameFirstname + nameDto14.NameLastName);  
                Console.WriteLine();  
                //Console.ReadKey();  
      
                //15.将Dictionary转化为对象,现在还不支持  
                Mapper.Reset();  
                Mapper.CreateMap<Dictionary<string, object>, Name>();  
                Dictionary<string, object> dict = new Dictionary<string, object>();  
                dict.Add("FirstName", "L");  
                //Name name15 = Mapper.DynamicMap<Dictionary<string, object>, Name>(dict);  
                Name name15 = Mapper.Map<Dictionary<string, object>, Name>(dict);  
                Console.WriteLine("15");  
                Console.WriteLine(name15.FirstName);  
                Console.WriteLine();  
                Console.ReadKey();  
            }  
        }  
      
      
        public class Store  
        {  
            public Name Name { get; set; }  
            public int Age { get; set; }  
        }  
      
        public class Name  
        {  
            public string FirstName { get; set; }  
            public string LastName { get; set; }  
        }  
      
        public class StoreDto  
        {  
            public NameDto Name { get; set; }  
            public int Age { get; set; }  
        }  
      
        public class NameDto  
        {  
            public string FirstName { get; set; }  
            public string LastName { get; set; }  
            public string AllName { get; set; }  
        }  
      
        public class FlattenName  
        {  
            public string NameFirstname { get; set; }  
            public string NameLastName { get; set; }  
        }  
      
        public class NameConverter : TypeConverter<Name, NameDto>  
        {  
            protected override NameDto ConvertCore(Name source)  
            {  
                return new NameDto() { AllName = source.FirstName + source.LastName };  
            }  
        }  
      
        public class NameResolver : ValueResolver<Name, NameDto>  
        {  
            protected override NameDto ResolveCore(Name source)  
            {  
                return new NameDto() { FirstName = source.FirstName, LastName = source.LastName,AllName=source.FirstName+source.LastName };  
            }  
        }  
      
        public class NameFormatter : ValueFormatter<NameDto>  
        {  
            protected override string FormatValueCore(NameDto name)  
            {  
                return name.FirstName + name.LastName;  
            }  
        }  
      
        public class StringFormatter : ValueFormatter<string>  
        {  
            protected override string FormatValueCore(string name)  
            {  
                return name + "-";  
            }  
        }  
    }  
  • 相关阅读:
    内联函数与宏定义
    三色塔汉诺塔 三色
    Volatile C
    阶乘 简单递归实现
    双色汉诺塔 算法 (递归)
    向上向下排序
    Convert、Parse、TryParse、(int)等区别
    ToString()、Convert.ToString()、(string)、as string 的区别[转]
    ASP.NET页面刷新方法大集合
    getElementByID,getElementsByName,getElementsByTagName的区别
  • 原文地址:https://www.cnblogs.com/vaevvaev/p/7080423.html
Copyright © 2020-2023  润新知