AutoMapper实现对象转换的几种方式

namespace ConsoleApplication1
{
    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));
            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特性
            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 };
        }
    }

    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 + "-";
        }
    }
}
时间: 2024-12-09 17:27:45

AutoMapper实现对象转换的几种方式的相关文章

C# 对象与JSON字符串互相转换的几种方式

出自:http://blog.csdn.net/testcs_dn/article/details/78150046?locationNum=6&fps=1 目录(?)[-] 方法一DoNet20 需要借助于NewtonsoftJsondll 方法二DataContractJsonSerializer 方法三JavaScriptSerializer 功能对比 性能对比 JSON转C实体类 相关参考 c json数据解析将字符串json格式数据转换成对象 Jsonnet实现方便的Json转Cdyn

对象属性复制几种方式

对象属性复制的三种方法: 1.Apache提供的BeanUtil.copyProperties和PropertyUtil.copyProperties两种方式 BeanUtils.copyProperties("转换后的类", "要转换的类"); PropertyUtils.copyProperties("转换后的类", "要转换的类"); 口诀:后付钱(后付前:后面的复制给前面) 2.spring提供的BeanUtil.co

word HTML文件与Markdwon互相转换的几种方式

Tip:word文件与Markdwon转换往往是可逆的.无论使用哪种方式,要想完美转换,必须要预先处理掉markdown与word不兼容的格式,如word文件对象,带边框的代码块等等 方法一:借助pandoc 或者结合Writage 下载地址https://pandoc.org/installing.html 也可从国内网站下载,最好是msi后缀的(会自动添加path). 如果安装来Anaconda 可以直接使用 无需下载 Linux: sudo apt-get install pandoc 使

【转】java中byte数组与int类型的转换(两种方式)----不错

原文网址:http://blog.csdn.net/piaojun_pj/article/details/5903009 java中byte数组与int类型的转换,在网络编程中这个算法是最基本的算法,我们都知道,在socket传输中,发送.者接收的数据都是 byte数组,但是int类型是4个byte组成的,如何把一个整形int转换成byte数组,同时如何把一个长度为4的byte数组转换为int类型.下面有两种方式. 第一种方法: public static byte[] int2byte(int

对象继承的几种方式

一. 对象冒充(又分为2种方式): 对象冒充方式的继承,只能继承父类函数内的属性,不能继承父类原型中的属性 方式一:   1. 让父类的构造函数成为子类的方法;                 2. 给子类的这个方法传入父类所拥有的属性,这就继承了父类的一些属性;                 3. 再在子类中删除这个方法;                                  function Child(name, age) {                     this

java中byte数组与int类型的转换(两种方式)

java中byte数组与int类型的转换,在网络编程中这个算法是最基本的算法,我们都知道,在socket传输中,发送.者接收的数据都是 byte数组,但是int类型是4个byte组成的,如何把一个整形int转换成byte数组,同时如何把一个长度为4的byte数组转换为int类型.下面有两种方式. 方法一 /** * int到byte[] * @param i * @return */ public static byte[] intToByteArray(int i) { byte[] resu

C++中对象创建的两种方式

在C++中,类的对象建立分为两种,一种是静态建立,如A a:另一种是动态建立,如A* ptr=new A:这两种方式是有区别的. 静态建立一个类对象,是由编译器为对象在栈空间中分配内存,是通过直接移动栈顶指针,挪出适当的空间,然后在这片内存空间上调用构造函数形成一个栈对象.使用这种方法,直接调用类的构造函数. 动态建立类对象,是使用new运算符将对象建立在堆空间中.这个过程分为两步,第一步是执行operator new()函数,在堆空间中搜索合适的内存并进行分配:第二步是调用构造函数构造对象,初

JS对象继承的几种方式总结

今天学习了一下js的继承,js中的继承主要分四种,原型继承,构造函数继承,call/apply继承以及es6的extend继承.1.原型继承:原型继承主要利用js对象的prototype引用父类的构造函数来复制父类的方法. //定义一个Person类 function Person(name){ this.name=name; } //打招呼 Person.prototype.sayHello=function(){ alert("Hello,my name is "+this.nam

直接调用对象方法的两种方式

关于直接调用方法和给对象发送消息调用方法(即perfromSelector和NSInvocation) performSelector是运行时系统负责去找方法的,在编译时候不做任何校验:如果直接调用编译是会自动校验.如果imageDownloader:didFinishWithImage:image:不存在,那么直接调用 在编译时候就能够发现(借助Xcode可以写完就发现),但是使用performSelector的话一定是在运行时候才能发现(此时程序崩溃):Cocoa支持在运行时向某个类添加方法