Automapper的用途是什么? [英] What's Automapper for?
问题描述
Automapper 的用途是什么?
它对我的域和控制器层(asp.net mvc)有什么帮助?
How will it help me with my domain and controller layers (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; }
}
}
到目前为止,这还算很轻松,但是现在呢?我们如何将一堆OrderDetail
变成一堆OrderDetailDto
进行数据绑定?
That was pretty painless so far, but what now? How do we turn a bunch of OrderDetail
s into a bunch of OrderDetailDto
s for data binding?
您可能会在OrderDto
上放置一个构造器,该构造器需要一个OrderDetail
,并编写大量的映射代码.或者您可能在某个地方有一个静态转换类.或者,您可以使用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;
在那里.我们已经采用了原本会令人厌恶的无意义的映射代码,然后将其简化为三行(对于实际映射,实际上只有两行).
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).
这有助于解释目的吗?
这篇关于Automapper的用途是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!