gpt4 book ai didi

asp.net - Automapper 有什么用?

转载 作者:行者123 更新时间:2023-12-03 13:24:53 25 4
gpt4 key购买 nike

什么是 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com