我具有以下产品映射,该映射将调用依赖项(ProductMapService中的UpdateProduct)在初始映射之后执行到产品子实体的映射。但是,当我执行映射过程时,会收到异常(未为此对象定义无参数的构造函数。)
我不确定这是在概要文件类中注入依赖项的最佳方法。有人可以建议我吗?
Automapper产品资料:
namespace MyAPI.Mappers
{
public class ProductProfiles: Profile
{
private readonly IProductMapService _productMap;
public ProductProfiles(IProductMapService productMap)
{
_productMap = productMap;
CreateMap<ProductForCreationDto, Product>();
CreateMap<ProductForUpdateDto, Product>()
.ForMember(p => p.VariOptions, opt => opt.Ignore())
.AfterMap((pDto, p) => _productMap.UpdateProduct(pDto, p));
}
}
}
ProductService.cs:
namespace MyAPI.Services
{
public class ProductMapService: IProductMapService
{
private readonly IMapper _mapper;
public ProductMapService(IMapper mapper)
{
_mapper = mapper;
}
public void UpdateProduct(ProductForUpdateDto productForUpdateDto, Product productFromRepo)
{
foreach (var variOptionDto in productForUpdateDto.VariOptions)
{
if(variOptionDto.Id == 0)
{
productFromRepo.VariOptions.Add(Mapper.Map<VariOption>(variOptionDto));
}
else
{
_mapper.Map(variOptionDto, productFromRepo.VariOptions.SingleOrDefault(vo => vo.Id == variOptionDto.Id));
}
foreach (var variOptionTwoDto in variOptionDto.VariOptionTwos)
{
if(variOptionTwoDto.Id == 0)
{
productFromRepo.VariOptions.FirstOrDefault(vo => vo.Id == variOptionDto.Id).VariOptionTwos.Add(Mapper.Map<VariOptionTwo>(variOptionTwoDto));
}
else
{
_mapper.Map(variOptionTwoDto, productFromRepo.VariOptions.FirstOrDefault(vo => vo.Id == variOptionDto.Id).VariOptionTwos.SingleOrDefault(vot => vot.Id == variOptionTwoDto.Id));
}
}
}
}
}
}
并在Startup.cs中:
services.AddAutoMapper();
services.AddSingleton<IProductMapService, ProductMapService>();
答案 0 :(得分:1)
我遵循了Lucian发布的文档,并创建了IMappingAction。
namespace PortalestAPI.Mappers.MappingActions
{
public class ProductVariationTwoUpdateAction: IMappingAction<VariOptionForUpdateDto, VariOption>
{
private readonly IProductMapService _productMapService;
public ProductVariationTwoUpdateAction(IProductMapService productMapService)
{
_productMapService = productMapService;
}
public void Process(VariOptionForUpdateDto variOptionForUpdateDto, VariOption variOption)
{
_productMapService.UpdateVariationTwo(variOptionForUpdateDto, variOption);
}
}
}