【发布时间】:2015-07-30 21:48:06
【问题描述】:
我有这种情况:
// Core Business classes
public class Invoice
{
public Guid Id { get; protected set; }
public int Number { get; set; }
public IList<InvoiceItem> Items { get; protected set; }
}
public class InvoiceItem
{
public Guid Id { get; protected set; }
public string Product { get; set; }
public int Quantity { get; set; }
public decimal Price { get; set; }
}
// MVC Models
public class InvoiceModel
{
public Guid Id { get; set; }
public int Number { get; set; }
public IList<InvoiceItemModel> Items { get; set; }
}
public class InvoiceItemModel
{
public Guid Id { get; set; }
public string Product { get; set; }
public int Quantity { get; set; }
public decimal Price { get; set; }
}
自动映射器配置
public class MyProfile : Profile
{
protected override void Configure()
{
Mapper.CreateMap<Invoice, InvoiceModel>();
Mapper.CreateMap<InvoiceItem, InvoiceItemModel>();
}
}
然后,当我想将模型传递给我的视图时,例如编辑 Invoice 对象,我会这样做:
...
var invoice = Repository.Get<Invoice>(id);
return View("Update", Mapper.Map<InvoiceModel>(invoice));
...
然后我可以使用 InvoiceItemModels 迭代 Items 集合。
问题是当我想检索一堆发票时,例如在索引中。
...
var invoices = Repository.ListAll<Invoice>();
return View("Index", invoices.Select(Mapper.Map<InvoiceModel>).ToList());
...
我不想加载“项目”。这种情况下更好的配置是:
public class MyFlatProfile : Profile
{
protected override void Configure()
{
Mapper.CreateMap<Invoice, InvoiceModel>()
.ForMember(m => m.Items, opt => opt.Ignore());
Mapper.CreateMap<InvoiceItem, InvoiceItemModel>();
}
}
但我不知道如何在“个人资料”之间切换。 有没有办法“选择”特定的映射配置?
【问题讨论】:
标签: c# asp.net-mvc automapper