在 AutoMapper 中切换配置

Switch between configurations in AutoMapper

我遇到这种情况:

// 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>();
    }
}

然后当我想将模型传递到我的视图时,例如编辑发票对象,我会这样做:

...
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());   
...

我不想加载 "Items"。这种情况下更好的配置是:

public class MyFlatProfile : Profile
{
    protected override void Configure()
    {
        Mapper.CreateMap<Invoice, InvoiceModel>()
            .ForMember(m => m.Items, opt => opt.Ignore());

        Mapper.CreateMap<InvoiceItem, InvoiceItemModel>();
    }
}

但是我不知道如何在"Profiles"之间切换。 有没有办法 "pick" 特定的映射配置?

不幸的是,您必须创建单独的 Configuration 对象,并为每个对象创建一个单独的 MappingEngine。

首先,清除静态 class 来保存映射器

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));