AutoMapper-类型的条件映射
本文关键字:映射 条件 类型 AutoMapper- | 更新日期: 2023-09-27 18:28:01
我想做以下事情,我想知道是否有人知道如何做:
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行来返回正确的类,那就太酷了。)
谢谢!
您可以只映射到基类吗?如果是,则可以在映射中使用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();
}