1

我的应用程序需要显示一个客户数据表,其中包括有关客户的数据以及他从给定仓库中的最新订单的数据。客户域对象包含一个 GetLatestOrder(warehouseId) 方法。

我有一个 CustomerView 视图模型,并希望能够使用来自客户对象的一些字段以及来自最新订单对象的一些字段来填充它。我可以使用 Automapper 执行此操作吗?

4

3 回答 3

4

尝试这个,

Global.asax.cs[ Application_Start] 中,public static void AppInitialize()

    protected void Application_Start(object sender, EventArgs e)
    {
        Mapper.CreateMap<Order, CustomerViewModel>()
             .ForMember(destination => destination.OrderId, options => options.MapFrom(source => source.Id))
             .ForMember(destination => destination.OrderName, options => options.MapFrom(source => source.Name));
        Mapper.CreateMap<Customer, CustomerViewModel>()
             .ForMember(destination => destination.CustmerId, options => options.MapFrom(source => source.Id))
             .ForMember(destination => destination.CustmerName, options => options.MapFrom(source => source.Name))
             .ForMember(destination => destination.OrderId, options => options.MapFrom(source => Mapper.Map<IEnumerable<Order>, IEnumerable<CustomerViewModel>>(source.Orders).FirstOrDefault().OrderId))
             .ForMember(destination => destination.OrderName, options => options.MapFrom(source => Mapper.Map<IEnumerable<Order>, IEnumerable<CustomerViewModel>>(source.Orders).FirstOrDefault().OrderName));
    }

在您的代码中调用映射器,如下所示,

        var lstCustomers = new List<Customer>
        {
            new Customer { Id = 1, Name="Name", Orders = new List<Order> { new Order { Id = 1000, Name ="Some Name"}}},
        };

        var result = Mapper.Map<IEnumerable<Customer>, IEnumerable<CustomerViewModel>>(lstCustomers);

我推测你的课程如下所示,

public class Customer
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<Order> Orders { get; set; }
}

public class Order
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class CustomerViewModel
{
    public int CustmerId { get; set; }
    public string CustmerName { get; set; }
    public int OrderId { get; set; }
    public string OrderName { get; set; }
}

另请参阅此帖子

于 2012-11-13T05:08:21.327 回答
1

是的你可以:

var vm = new CustomerViewModel();
Mapper.Map(customer, vm);
Mapper.Map(order, vm);

每个映射将填充它配置的属性并保留其余部分。

于 2012-11-12T17:54:59.867 回答
1

最后,我采取了简单的方法,找不到另一种方法:

在 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);
    }
于 2012-11-13T10:13:26.137 回答