asp.net - Automapper 有什么用?

标签 asp.net .net asp.net-mvc automapper

什么是 Automapper为了?

它将如何帮助我处理我的域和 Controller 层(asp.net mvc)?

最佳答案

也许一个例子在这里会有所帮助......

假设您有一个很好的标准化数据库模式,如下所示:

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

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 s 成一堆 OrderDetailDto s 用于数据绑定(bind)?

您可以在 OrderDto 上放置一个构造函数这需要 OrderDetail ,并写了一大堆映射代码。或者您可能在某处有一个静态转换类。或者,您可以使用 AutoMapper,并改为:
Mapper.CreateMap<OrderDetail, OrderDetailDto>();
OrderDetailDto[] items =
    Mapper.Map<OrderDetail[], OrderDetailDto[]>(orderDetails);
GridView1.DataSource = items;

那里。我们刚刚采用了原本会令人作呕的毫无意义的映射代码,并将其缩减为三行(实际上只有两行用于实际映射)。

这有助于解释目的吗?

关于asp.net - Automapper 有什么用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2090915/

相关文章:

asp.net - 如何从javascript控制用户控件

asp.net - 无法让 sourcemap 工作

c# - 反编译.Net代码: lambda expressions

.net - 为什么.net中没有异步文件删除功能?

asp.net - asp.net中的SqlDependency

asp.net - facebook api 错误代码 : 191 Asp. 使用开发环境 localhost 和 ACS 的 Net MVC 3

c# - 返回 json 的 <T> 字符串

asp.net - 如何在 .net 中阻止 libwww-perl 访问?

asp.net-mvc - 如何在 Asp.Net MVC 中发布部分帖子?

asp.net-mvc - 使用 Razor View Engine 在 ASP.NET MVC3 中通过传递参数运行更改 DropDownListFor 的操作