官网:

文档:

github:https://github.com/automapper/automapper/blob/master/docs/index.rst

什么是automapper?

  automapper是一个对象-对象映射器。对象-对象映射通过将一种类型的输入对象转换为另一种类型的输出对象来工作。使automapper变得有趣的是,它提供了一些有趣的约定,以免去搞清楚如何将类型a映射为类型b。只要类型b遵循automapper既定的约定,就需要几乎零配置来映射两个类型。

为什么要使用automapper?

  映射代码很无聊。测试映射代码更加无聊。automapper提供了简单的类型配置以及简单的映射测试。真正的问题可能是“为什么使用对象-对象映射?”映射可以在应用程序中的许多地方发生,但主要发生在层之间的边界中,例如ui /域层或服务/域层之间。一层的关注点通常与另一层的关注点冲突,因此对象-对象映射导致分离的模型,其中每一层的关注点仅会影响该层中的类型。

automapper的使用场景:

  automapper是对象到对象的映射工具。在完成映射规则之后,automapper可以将源对象转换为目标对象。
一般情况下,表现层与应用层之间是通过dto(数据传输对象data transfer object)来进行交互的,数据传输对象是没有行为的poco对象(简单clr对象plain old clr object),他的目的是为了对领域对象进行数据封装,实现层与层之间的数据传递。为何不直接将领域对象进行数据传递?因为领域对象更注重领域,dto更注重数据。由于“富领域模型”的特点,这样会直接将领域对象的行为暴露给表现层。
dto本身不是业务对象,它是根据ui需求进行设计的。简单来说model面向业务,我们是通过业务来定义model的。而dto是面向ui,通过ui的需求来定义的,通过dto我们实现了表现层与model层之间的解耦,表现层不引用model。如果开发过程中我们的模型变了,而界面没变,我们只需改model而不需要去改动表现层。

如何使用automapper?

  首先,您需要同时使用源类型和目标类型。目标类型的设计可能会受到其所在层的影响,但是只要成员名称与源类型的成员匹配,automapper的效果最佳。如果您有一个名为“ firstname”的源成员,它将自动映射到名称为“ firstname”的目标成员。automapper还支持flattening。

  将源映射到目标时,automapper将忽略空引用异常。这是设计使然。如果您不喜欢这种方法,则可以根据需要将automapper的方法与自定义值解析器结合使用。

如何在dotnet core中使用automapper?

首先,要安装依赖包:

 

 在startup.cs中利用dotnet core自带的容器进行注入,因为我里面是示例代码,新建的示例demo也没有去改名字,也都是在同一个命名空间下的,但是在实际项目中是不会出现这种问题的

//添加对automapper的支持
services.addautomapper(assembly.load("webapplication1"), assembly.load("webapplication1"));

 即下图所示的关系:

源类型model对象,与映射后的dto类型:

 public class userinfo
 {
     public string username { get; set; }

     public string userpwd { get; set; }

     public string getcreatetime { get; set; }

 }
public class userinfodto
{
    public string username { get; set; }

    public string userpwd { get; set; }

    public string role { get; set; }

    public datetime createtime { get; set; }

    public string testtime { get; set; }
}

profile的用法:

  profile提供了一个命名的映射类,所有继承自profile类的子类都是一个映射集合。这里我们创建一个userprofile继承profile类。

  createmap:创建映射规则。

  beforemap:在映射之前执行的方法。

  aftermap:反之,映射之后执行的方法。

  自动化扁平映射:automapper会将类中的属性进行分割,或匹配”get”开头的方法。

  formember:指定映射字段。

public class userprofile : profile
{
    //添加你的尸体映射关系
    public userprofile()
    {
        createmap<userinfo, userinfodto>()
            .beforemap((source, dto) =>
            {
                //可以较为精确的控制输出数据格式
                if (string.isnullorempty(source.getcreatetime))
                {
                    source.getcreatetime = convert.todatetime(source.getcreatetime).tostring("yyyy-mm-dd");
                }
            })
            //指定映射字段。将userinfo.getcreatetime映射到userinfodto.testtime
            .formember(dto => dto.testtime, opt => opt.mapfrom(info => info.getcreatetime))
            .formember(dto => dto.role, opt => opt.ignore())
            .formember(dto => dto.createtime, opt => opt.ignore());

        createmap<studentinfo, userinfo>();
    }
}

控制器注入imapper:

private readonly imapper _mapper;

public homecontroller(imapper mapper)
{
    _mapper = mapper;
}

单个对象转dto:

//模拟数据
var user = new userinfo()
{
    username = "bingle",
    userpwd = "12345"
};
var userdto = _mapper.map<userinfodto>(user);

集合转dto集合:

//模拟数据
var userlist = new list<userinfo>
{
    new userinfo
    {
        username="bingle_1",
        userpwd="1"
    },
    new userinfo
    {
        username="bingle_2",
        userpwd="2"
    },
    new userinfo
    {
        username="bingle_3",
        userpwd="3"
    },
    new userinfo
    {
        username="bingle_4",
        userpwd="4"
    },
    new userinfo
    {
        username="bingle_5",
        userpwd="5"
    },
    new userinfo
    {
        username="bingle_6",
        userpwd="6"
    }
};
//对象集合转dto集合
var usersdtos = _mapper.map<list<userinfodto>>(userlist);

  automapper功能很强大,在这边介绍的只是很少的功能,有兴趣的伙伴可以去automapper官方文档深入学习。

  如果有小伙伴觉得在使用automapper都得在controller的构造函数中进行注入一遍麻烦的话,automapper也是支持这种映射方式如:mapper.map

实例方式:

//模拟数据
var user = new userinfo()
{
    username = "bingle",
    userpwd = "12345"
};
var config = new mapperconfiguration(cfg => cfg.createmap<userinfo, userinfodto>());
var mapper = config.createmapper();

var userdto = mapper.map<userinfodto>(user);

参考: