我从旧版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>'`.
我做错了什么?我怀疑我没有正确理解新的自定义解析器接口。
short?
表示ModelId,并且我希望能够重复使用相同的解析器。 - Petrus Theron.ForMember(dest => dest.ModelCode ...
,其中目标是 TSource(类型为 Product)上的short?
属性,而源是字符串。 - Petrus TheronIMemberValueResolver
从源类型String
解析目标类型为List<Dto>
的值,但它从未起作用。您能提供任何有效的存储库吗?谢谢; - Robin