AutoMapper - Conditional Mapping for Type

前端 未结 1 602
北恋
北恋 2021-01-22 11:07

I\'d like to do something like the following and I\'m wondering if someone knows how to do it:

Mapper.CreateMap().If(pWorksh         


        
相关标签:
1条回答
  • 2021-01-22 11:35

    Instead of mapping V2WorksheetModel and V3WorksheetModel can you map just to the base class? If yes you can then use ConstructUsing in your mapping:

    [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();
    }
    
    0 讨论(0)
提交回复
热议问题