我有一个 MVC 应用程序,并且已经开始专门使用 DTO 来将数据发送到视图。我使用 AutoMapper 来简化这个过程。
想象一下我有一个有很多订单的客户。要显示简单的客户概览页面,我可以使用 AutoMapper 和一个简单的 DTO 类来映射客户名称、地址等。要映射订单,我可以使用 AutoMapper 列表<>将 Customer.Orders 转换为更简单的列表。
我现在卡在我希望两个页面处于同一视图中的页面上。也许是一个简单的标题,其中包含客户姓名和电话号码,然后是订单列表。在某些情况下,部分是完美的解决方案,但不是全部。
所以我的问题是这样的页面的 DTO 应该是什么样子,以及应该如何映射它(最好使用 AutoMapper)。到目前为止,在我的研究中,我看不到 AutoMapper 如何能够像这样映射嵌入式枚举。
I have an MVC app and I have started to use DTOs exclusively to send data to views. I am using AutoMapper in order to ease this process.
Imagine I have a Customer that has many Orders. To display a simple customer overview page I can use AutoMapper with a simple DTO class that maps the Customer name, address etc. To map the orders I can AutoMapper a List<> of Customer.Orders to a more simple List<CustomerOrderDTO>.
I am now stuck on pages where I want both in the same view. Perhaps a simple headline with the customer name and phone number, then a list of orders. In some cases partials are the perfect solution, but not all.
So my question is how a DTO for a page such as this should look, and how that should be mapped (preferably using AutoMapper). In my research so far, I can't see how AutoMapper can map embedded enumerables like this.
发布评论
评论(1)
当您创建映射时,忽略集合/枚举,仅将简单对象映射到简单对象,例如
CreateMap()
当您执行映射时,您可以使用集合,AutoMapper 将只需做正确的事情,例如
Map, IEnumerable>()
如果您要映射包含集合的对象,例如
Customer
到CustomerDTO
,其中每个都有其订单集合,只要您为客户对象完成了CreateMap
并为客户对象完成了CreateMap
Order
对象,枚举将自动映射,除非您在客户映射中专门将其设置为忽略。when you create your mappings, ignore the collections/enumerables and just map simple objects to simple objects, for example
CreateMap<Order, CustomerOrderDTO>()
when you execute the mapping, you can use collections and AutoMapper will just do the right thing, for example
Map<IEnumerable<Order>, IEnumerable<CustomerOrderDTO>>()
if you're mapping an object contains the collection, for example
Customer
toCustomerDTO
, where each one has it's collection of orders, as long as you've doneCreateMap
for the customer objects andCreateMap
for theOrder
objects, the enumerable will just map automatically, unless you specifically set it to be ignored in the customer mapping.