AutoMapper扁平化处理

文档地址:https://automapper.readthedocs.io/en/latest/Flattening.html

对象-对象的映射,最常见的应用就是将一个复杂的对象模型映射到一个简单的对象模型。如有如下复杂模型:

public class Order
{
    private readonly IList<OrderLineItem> _orderLineItems = new List<OrderLineItem>();

    public Customer Customer { get; set; }

    public OrderLineItem[] GetOrderLineItems()
    {
        return _orderLineItems.ToArray();
    }

    public void AddOrderLineItem(Product product, int quantity)
    {
        _orderLineItems.Add(new OrderLineItem(product, quantity));
    }

    public decimal GetTotal()
    {
        return _orderLineItems.Sum(li => li.GetTotal());
    }
}

public class Product
{
    public decimal Price { get; set; }
    public string Name { get; set; }
}

public class OrderLineItem
{
    public OrderLineItem(Product product, int quantity)
    {
        Product = product;
        Quantity = quantity;
    }

    public Product Product { get; private set; }
    public int Quantity { get; private set;}

    public decimal GetTotal()
    {
        return Quantity*Product.Price;
    }
}

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

我们想将这个复杂模型:Order对象映射到下面这个简单的对象模型OrderDto中

public class OrderDto
{
    public string CustomerName { get; set; }
    public decimal Total { get; set; }
}

当使用AutoMapper进行源/目标类型配对是,配置选项会默认使用源类型上的属性和方法与目标类型上的属性进行匹配。对于目标类型上的任何属性,如果源类型上不存在属性、方法或前缀为“Get”的方法时,AutoMapper将对目标成员属性进行单词拆分(按照PascalCase约定)。

// Complex model
var customer = new Customer
    {
        Name = "George Costanza"
    };
var order = new Order
    {
        Customer = customer
    };
var bosco = new Product
    {
        Name = "Bosco",
        Price = 4.99m
    };
order.AddOrderLineItem(bosco, 15);

// Configure AutoMapper
Mapper.Initialize(cfg => cfg.CreateMap<Order, OrderDto>());

// Perform mapping
OrderDto dto = Mapper.Map<Order, OrderDto>(order);

dto.CustomerName.ShouldEqual("George Costanza");
dto.Total.ShouldEqual(74.85m);

使用CreateMap方法在AutoMapper中配置类型映射。因AutoMapper只能对它知道的类型匹配,我们显示注册了源/目标类型匹配对象。想要执行映射方法,要使用Map方法。

对于OrderDto类型,Total属性与Order上的GetTotal()方法匹配。CustomerName属性与Order上的Customer.Name属性匹配。


 

猜你喜欢

转载自blog.csdn.net/weixin_42930928/article/details/84643005