我从旧版本的 AutoMapper 升级并转换了我的自定义解析器,但我遇到了困难。
public class ProductMappingProfile : Profile
{
public ProductMappingProfile()
{
CreateMap<Product, ProductViewModel>()
.ForMember(
dest => dest.Model,
opt => opt.ResolveUsing<ModelNameResolver>(src => src.ModelId));
// won't compile
}
}
Product 有一个int? ModelId
属性,ProductViewModel 有一个string Name
属性。
自定义解析器
public class ModelNameResolver : IValueResolver<short?, string, string>
{
private readonly InventoryService _inventoryService;
public ModelNameResolver(InventoryService inventoryService)
{
_inventoryService = inventoryService;
}
public string Resolve(short? source, string destination, string destMember, ResolutionContext context)
{
if (!source.HasValue)
return "n/a";
return _inventoryService.GetModel(source.Value)
.Name;
}
}
编译错误:
The type 'MyNamespace.Web.Resolvers.ModelCodeResolver' cannot be used as type parameter 'TValueResolver' in the generic type or method `'AutoMapper.IMemberConfigurationExpression<TSource,TDestination,TMember>.ResolveUsing<TValueResolver>()'`.
There is no implicit reference conversion from `'MyNamespace.Web.Resolvers.ModelCodeResolver'` to `'AutoMapper.IValueResolver<Data.Models.Product,Web.ViewModels.ProductViewModel,string>'`.
我究竟做错了什么?我怀疑我误解了新的自定义解析器界面。