请告诉我Automapper呢? [英] Whats Automapper for?

查看:141
本文介绍了请告诉我Automapper呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是 Automapper 呢?它将如何帮助我的域和控制器层(asp.net MVC)

What’s Automapper for? How will it help me with my domain and controller layer (asp.net mvc)

推荐答案

也许一个例子将有助于在这里...

Maybe an example will help here...

比方说,你有这样一个很好的规范化数据库模式:

Let's say you have a nicely-normalized database schema like this:


Orders       (OrderID, CustomerID, OrderDate)  
Customers    (CustomerID, Name)  
OrderDetails (OrderDetID, OrderID, ProductID, Qty)  
Products     (ProductID, ProductName, UnitPrice)  

和假设你正在使用一个很好的O / R映射器递给你回到一个组织良好的域模型:

And let's say you're using a nice O/R mapper that hands you back a well-organized domain model:


OrderDetail
+--ID
+--Order
|--+--Date
|--+--Customer
|-----+--ID
|-----+--Name
+--Product
|--+--ID
|--+--Name
|--+--UnitPrice
+--Qty

现在你给的要求,以显示这就是被下令在上个月的一切。要绑定这一个平面网格,所以你尽职尽责地写一个平级的绑定:

Now you're given a requirement to display everything that's been ordered in the last month. You want to bind this to a flat grid, so you dutifully write a flat class to bind:

public class OrderDetailDto
{
    public int ID { get; set; }
    public DateTime OrderDate { get; set; }
    public int OrderCustomerID { get; set; }
    public string OrderCustomerName { get; set; }
    public int ProductID { get; set; }
    public string ProductName { get; set; }
    public Decimal ProductUnitPrice { get; set; }
    public int Qty { get; set; }

    public Decimal TotalPrice
    {
        get { return ProductUnitPrice * Qty; }
    }
}

这是pretty的无痛性,到目前为止,但现在该怎么办?我们如何把一堆的OrderDetail 的S成一束 OrderDetailDto 的S数据绑定?

That was pretty painless so far, but what now? How do we turn a bunch of OrderDetails into a bunch of OrderDetailDtos for data binding?

您可以把一个构造函数 OrderDto 接受一个的OrderDetail ,写的映射$ C一团糟$ C。或者你可能有一个静态转换类的地方。或者,你可以使用AutoMapper,而是写:

You might put a constructor on OrderDto that takes an OrderDetail, and write a big mess of mapping code. Or you might have a static conversion class somewhere. Or, you could use AutoMapper, and write this instead:

Mapper.CreateMap<OrderDetail, OrderDetailDto>();
OrderDetailDto[] items =
    Mapper.Map<OrderDetail[], OrderDetailDto[]>(orderDetails);
GridView1.DataSource = items;

有。我们刚刚采取了哪些否则将是毫无意义的映射code令人作呕的烂摊子,降低成三条线(实际上它是两个实际映射)。

There. We've just taken what would otherwise have been a disgusting mess of pointless mapping code and reduced it into three lines (really just two for the actual mapping).

这是否有助于解释的目的是什么?

Does that help explain the purpose?

这篇关于请告诉我Automapper呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆