如何使用Automapper从一个简单的对象和方法调用创建复杂的视图模型对象 [英] How to use Automapper to create complex viewmodel objects from a simple object and a method call

查看:159
本文介绍了如何使用Automapper从一个简单的对象和方法调用创建复杂的视图模型对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序需要显示客户资料,包括有关客户和有关他最近从指定仓库订单数据表。客户域对象包含GetLatestOrder(warehouseId)方法。

My application needs to display a table of customer data, including data about the customer and about his most recent order from a given warehouse. The customer domain object contains a GetLatestOrder(warehouseId) method.

我有一个CustomerView视图模型,并希望能够从客户对象的某些字段,并从最新的订单对象几个字段来填充它。我能做到这一点使用Automapper?

I have a CustomerView viewmodel and want to be able to populate it with some fields from the customer object, and a few fields from the latest order object. Can I do this using Automapper?

推荐答案

在最后,我带着简单的方法,无法找到另一种方式:

In the end, I took the easy approach, couldn't find another way:

在的Application_Start:

In Application_start:

    Mapper.CreateMap<Customer, CustomerView>();
    Mapper.CreateMap<Order, CustomerView>();

在控制器的方法:

    IEnumerable<Customer> customers = GetCustomers(false)
                                               .OrderBy(c => c.Name);
    IEnumerable<CustomerView> viewData = Mapper.Map<IEnumerable<Customer>, IEnumerable<CustomerView>>(customers);
    foreach (Customer customer in customers)
    {
        CustomerView view = viewData.Where(cv => cv.CustomerId == customer.CustomerId).First();
        Mapper.Map(customer.GetLatestOrder(WarehouseId), view);
    }

这篇关于如何使用Automapper从一个简单的对象和方法调用创建复杂的视图模型对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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