Problem auto mapping => collection of view models instead another view model

谁说胖子不能爱 提交于 2019-12-10 12:17:16

问题


I have something like this

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>();

When I have this I get

  • Trying to map OtherObjects to BViewModel
  • Using mapping configuration for SomeObject to AViewModel
  • Destination property: BVM
  • Missing type map configuration or unsupported mapping.
  • Exception of type 'AutoMapper.AutoMapperMappingException' was thrown.

How can I help it figure out how to map it properly?


回答1:


You need to specify a typeconverter between OtherObject and BViewModel by specifying a custom type converter

Here's what the converter would look like:

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; }
  }
}

And then the map would be called like this:

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



回答2:


I believe Automapper needs to know how to convert OtherObject to BViewModel. Try adding a mapping for that too.



来源:https://stackoverflow.com/questions/5691270/problem-auto-mapping-collection-of-view-models-instead-another-view-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!