是否可以使用Automapper将多个DTO对象映射到单个ViewModel?

我想知道是否可以使用Automapper将多个DTO对象映射到单个ViewModel对象?

本质上,我有多个DTO对象,并希望在ASP.NET MVC 2.0中的单个屏幕上显示每个对象的信息。 为此,我想将DTO对象(或其中的一部分……)展平到Viewmodel中,并将所述viewmodel传递给视图。 如果我有一个DTO,这将很容易,但我从来没有看到它完成多个。 显然,有很多迂回的方法可以做到这一点(在automapper之外),但这是我想要的方法,如果可能的话。

您可以创建一个包含两个或更多DTO对象的复合DTO,并将复合DTO映射到输出视图模型。

如果您有2个DTO类和1个展平视图模型:

public class Dto1 { public string Property1 { get; set; } } public class Dto2 { public string Property2 { get; set; } } public class FlattenedViewModel { public string Property1 { get; set; } public string Property2 { get; set; } } 

并为两个DTO创建映射以查看模型:

 CreateMap(); CreateMap(); 

您可以将1st DTO映射到模型,然后只需“追加”第二个DTO:

 var dto1 = new Dto1 { Property1 = "Value1"; } var dto2 = new Dto2 { Property2 = "Value2"; } var model = Mapper.Map(dto1); // map dto1 properties Mapper.Map(dto2, model); // append dto2 properties 

您可以在带有params数组的IMappingEngine上添加Map覆盖扩展方法。 就像是:

 public static class AutoMapperExtensions { public static T Map(this IMappingEngine engine, params object[] sources) where T : class { if (sources == null || sources.Length == 0) return default(T); var destinationType = typeof (T); var result = engine.Map(sources[0], sources[0].GetType(), destinationType) as T; for (int i = 1; i < sources.Length; i++) { engine.Map(sources[i], result, sources[i].GetType(), destinationType); } return result; } } 

然后你可以像这样调用它:

 var result = Mapper.Engine.Map(dto1, dto2, dto3); 

我只是自己解决了这个问题并提出了一个很好的解 您的两个视图很可能在您的系统中以某种方式实际相关(特别是如果您使用的是Entity Framework)。 检查您的模型,您应该看到显示关系的内容,如果您不这样做,则只需添加它。 ( virtual

你的模特

  public class Dto1 { public int id { get; set; } public string Property2 { get; set; } public string Property3 { get; set; } public string Property4 { get; set; } public string Property5 { get; set; } public virtual Dto2 dto2{ get; set; } } public class Dto2 { public int id { get; set; } public string PropertyB { get; set; } public string PropertyC { get; set; } public string PropertyD { get; set; } public string PropertyE { get; set; } } 

你的ViewModels

  public class Dto1ViewModel { public string Property1 { get; set; } public string Property2 { get; set; } public virtual Dto2VMForDto1 dto2{ get; set; } } //Special ViewModel just for sliding into the above public class Dto2VMForDto1 { public int id { get; set; } public string PropertyB { get; set; } public string PropertyC { get; set; } } 

Automapper看起来像这样:

  cfg.CreateMap< Dto1, Dto1ViewModel>(); cfg.CreateMap< Dto2, Dto2VMForDto1 >(); 

我假设您使用LinQ获取数据:

 Dto1ViewModel thePageVM = (from entry in context.Dto1 where...).ProjectTo(); 

中提琴,一切都会奏效。 在您的视图中,只需使用model.dto2.PropertyB访问