asp.net MVC - 问题自动映射 =>视图模型集合而不是另一个视图模型



我有这样的东西

public class AViewModel
{
    public decimal number { get; set; }
    public List<BViewModel> BVM { get; set; }
}
public class BViewModel
{
    public string someString{ get; set; }
}
public class SomeObject
{
    public decimal number { get; set; }
    public List<OtherObjects> BVM { get; set; }
}
public class OtherObjects {
    public string someString{ get; set; }
}
Mapper.CreateMap<SomeObject,AViewModel>();

当我有这个时,我得到

  • 尝试将OtherObjects映射到BViewModel
  • 使用SomeObject到AViewModel的映射配置
  • 目的属性:BVM
  • 缺少类型映射配置或不支持映射。
  • 类型为"AutoMapper"的异常。AutoMapperMappingException'被抛出。

我怎样才能帮助它找出如何正确地映射它?

我相信Automapper需要知道如何将OtherObject转换为BViewModel。

您需要通过指定自定义类型转换器来指定OtherObject和BViewModel之间的类型转换器

下面是转换器的样子:

public class OtherToBViewTypeConverter : ITypeConverter<OtherObjects, BViewModel>
{
  public BViewModel Convert(ResolutionContext context) 
  {
    if (context.IsSourceValueNull) return null;
    var otherObjects = context.SourceValue as OtherObjects;
    return new BViewModel { someString = otherObjects.someString; }
  }
}

然后像这样调用映射:

Mapper.CreateMap<SomeObject,AViewModel>().ConvertUsing<OtherToBViewTypeConverter>();

最新更新