我遇到这种情况:
// 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));
...
然后我可以使用InvoiceItemModel
s迭代Items集合。
问题在于我想要检索一堆发票,例如在索引中。
...
var invoices = Repository.ListAll<Invoice>();
return View("Index", invoices.Select(Mapper.Map<InvoiceModel>).ToList());
...
我不想要&#34; Items&#34;要加载。对于这种情况,更好的配置是:
public class MyFlatProfile : Profile
{
protected override void Configure()
{
Mapper.CreateMap<Invoice, InvoiceModel>()
.ForMember(m => m.Items, opt => opt.Ignore());
Mapper.CreateMap<InvoiceItem, InvoiceItemModel>();
}
}
但我不知道如何在&#34; Profiles&#34;之间切换。 有没有办法去挑选&#34;一种特殊的映射配置?
答案 0 :(得分:2)
不幸的是,您必须创建单独的Configuration对象,并为每个对象创建一个单独的MappingEngine。
首先,取消静态类来保存映射器
public static class MapperFactory
{
public static MappingEngine NormalMapper()
{
var normalConfig = new ConfigurationStore(new TypeMapFactory(), MapperRegistry.Mappers);
normalConfig.CreateMap<Invoice, InvoiceModel>();
normalConfig.CreateMap<InvoiceItem, InvoiceItemModel>();
var normalMapper = new MappingEngine(normalConfig);
return normalMapper;
}
public static MappingEngine FlatMapper()
{
var flatConfig = new ConfigurationStore(new TypeMapFactory(), MapperRegistry.Mappers);
flatConfig.CreateMap<Invoice, InvoiceModel>()
.ForMember(m => m.Items, opt => opt.Ignore());
flatConfig.CreateMap<InvoiceItem, InvoiceItemModel>();
var flatMapper = new MappingEngine(flatConfig);
return flatMapper;
}
}
然后您可以调用MappingEngine进行映射(语法与Mapper对象相同)。
return View("Update", MapperFactory.FlatMapper().Map<InvoiceModel>(invoice));
return View("Update", MapperFactory.NormalMapper().Map<InvoiceModel>(invoice));