问题
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