AutoMapper - Type的条件映射

时间:2012-03-17 02:10:41

标签: c# automapper

我想做类似以下的事情,我想知道是否有人知道怎么做:

Mapper.CreateMap<Worksheet, V2WorksheetModel>().If(pWorksheet=> pWorksheet.VisitLevel == 2);
Mapper.CreateMap<Worksheet, V3WorksheetModel>().If(pWorksheet=> pWorksheet.VisitLevel == 3);

Worksheet entityVisit2 = MyService.GetWorksheetByID(100); //visit level 2
Worksheet entityVisit3 = MyService.GetWorksheetByID(150); //visit level 3
WorksheetModelBase modelBase1 = Mapper.Map(entityVisit2);  
WorksheetModelBase modelBase2 = Mapper.Map(entityVisit3);  
Assert.True(modelBase is V2WorksheetModel);
Assert.True(modelBase2 is V3WorksheetModel);

所以我希望Mapper.Map()返回正确派生类型的WorksheetModelBase。这可能吗? (我知道我可以在调用代码中执行if语句,但如果我可以使用这一个Mapper.Map行来返回正确的类,那就太酷了。)

谢谢!

1 个答案:

答案 0 :(得分:3)

您可以只映射到基类,而不是映射V2WorksheetModel和V3WorksheetModel吗? 如果是,则可以在映射中使用ConstructUsing

[Test]
public void Test1()
{
    Mapper.CreateMap<Worksheet, WorksheetModelBase>().ConstructUsing(GetWorksheetModel);

    Worksheet entityVisit2 = new Worksheet { VisitLevel = 2 };
    Worksheet entityVisit3 = new Worksheet { VisitLevel = 3 };

    var modelBase1 = Mapper.Map<WorksheetModelBase>(entityVisit2);
    var modelBase2 = Mapper.Map<WorksheetModelBase>(entityVisit3);

    Assert.IsTrue(modelBase1 is V2WorksheetModel);
    Assert.IsTrue(modelBase2 is V3WorksheetModel);
}

private WorksheetModelBase GetWorksheetModel(ResolutionContext context)
{
    var worksheet = (Worksheet) context.SourceValue;
    if (worksheet.VisitLevel == 2)
        return new V2WorksheetModel();
    if (worksheet.VisitLevel == 3)
        return new V3WorksheetModel();
    return new WorksheetModelBase();
}