我们为什么要在对象之间做映射

处于耦合性或者安全性考虑或者性能考虑我们不希望将model模型传递给他们,我们会在项目中创建一些dto(data transfer object数据传输对象),进行数据的传输.

概述

agilemapper是一个零配置、高度可配置的对象-对象映射器,具有可查看的执行计划,目标是.net standard 1.0+和.net 3.5+.他执行查询映射、对象创建、深度克隆、id感知更新和合并,可以通过扩展方法、静态api或实例api使用.

快速开始

通过nuget安装agilemapper

pm> install-package agileobjects.agilemapper

 

基本用法

对象创建

  使用以下方法从另一个创建对象

var customer = mapper.map(customerviewmodel).toanew<customer>();
// or:
var customer = customerviewmodel.map().toanew<customer>();

查询映射

使用实体到另一个类型的使用

var customervm = await dbcontext
    .customers
    .project().to<customerviewmodel>()
    .firstasync(c => c.id == customerid);

深度克隆

var clonedcustomer = mapper.deepclone(customertobecloned);
// or:
var clonedcustomer = customertobecloned.deepclone();

更新

使用一下命令更新对象的成员与另一个值

mapper.map(customersaverequest).over(customer);
// or:
customersaverequest.map().over(customer);

合并

使用以下方法将对象未填充成员与另一个的值合并

mapper.map(customerdto).onto(customer);
// or:
customerdto.map().onto(customer);

忽略成员

 其中有没有目标成员匹配,兼容源成员默认情况下忽略,但你也可以告诉映射器忽略他.

public class orderdto
{
    public int id { get; set; }
}

public class order
{
    public int? id { get; set; }
    public datetime datecreated { get; set; }
}

order.datecreated将被忽略,因为orderdto没有匹配到,但是id属性将被更新,这一块可以停止更新

mapper.whenmapping
    .from<orderdto>()   // 从orderdto映射
    .to<order>()        // 将忽略订单创建更新合并
    .ignore(o => o.id); // 忽略了id属性

忽略多个字段,并且成立忽略条件

mapper
    .map(orderdto).over(order, cfg => cfg
        .if((dto, o) => dto.id == 0) // 忽略 orderdto.id为0
        .ignore(
            o => o.id,
            o => o.datecreated);     // 忽略id和datecreated

空结果

如果目标类成员没有匹配到,可以将他映射为null

例如:

var source = new { name = "frank" };
var target = new person { name = "charlie", address = default(address) };
mapper.map(source).over(target);

配置复杂类型返回null不进行实例化

mapper.whenmapping
    .toanew<address>()
    .if((o, a) => 
        string.isnullorwhitespace(a.line1) || 
        string.isnullorwhitespace(a.postcode))
    .maptonull();