AutoMapper-开源的对象之间的映射工具

需要使用Nuget安装

1)命令行

PM> Install-Package AutoMapper

2)Nuget管理窗口查找然后安装

 

下面是两个例子。

1) 不含嵌套类的类之间映射

public class People
{
    public string Name { get; set; }
}

public class Human
{
    public string Name { get; set; }
}

然后设置映射,转换。

public static void TestMapping()
{
    Mapper.CreateMap<People, Human>();

    Human h = Mapper.Map<Human>(new People { Name = "test" });

    Console.WriteLine(h.Name);
}

2)包含嵌套类的类之间的映射

public class People
{
    public string Name { get; set; }
    public Contact Contact { get; set; }
}

public class Contact
{
    public string Mobile { get; set; }
    public string Email { get; set; }
}

public class Human
{
    public string Name { get; set; }
    public ContactDetail Contact { get; set; }
}

public class ContactDetail
{
    public string Mobile { get; set; }
    public string Email { get; set; }
}

需要为嵌套的每一个类设置映射(不只是第一层的类)

public static void TestNestedMapping()
{
    Mapper.Initialize(cfg =>
    {
        cfg.CreateMap<People, Human>();
        cfg.CreateMap<Contact, ContactDetail>();
    });

    Human h = Mapper.Map<People, Human>(new People
    {
        Name = "test",
        Contact = new Contact
        {
            Mobile = "1231456",
            Email = "a@a.com"
        }
    });
    var s = new XmlSerializer(typeof(Human));
    using (StringWriter textWriter = new StringWriter())
    {
        s.Serialize(textWriter, h);
        Console.WriteLine(textWriter.ToString());
    }
}

 

参考:


http://automapper.org/

https://github.com/AutoMapper/AutoMapper

https://www.nuget.org/packages/AutoMapper/3.2.1

posted @ 2016-06-12 11:11  一点一滴,日积月累  阅读(248)  评论(0)    收藏  举报