AutoMapper 是否没有本地方法来更新需要删除、添加或更新实例的嵌套列表?
我在带有 EF Core 的 ASP.Net Core 应用程序中使用 AutoMapper 将我的 API 资源映射到我的模型。这对我的大多数应用程序来说都运行良好,但我对更新映射嵌套列表的解决方案不满意,其中列出的实例需要保留。我不想覆盖现有列表,我想删除传入资源中不再存在的实例、添加新实例并更新现有实例。
型号:
public class MainObject
{
public int Id { get; set; }
public List<SubItem> SubItems { get; set; }
}
public class SubItem
{
public int Id { get; set; }
public int MainObjectId { get; set; }
public MainObject MainObject { get; set; }
public double Value { get; set; }
}
资源:
public class MainObjectResource
{
public int Id { get; set; }
public ICollection<SubItemResource> SubItems { get; set; }
}
public class SubItemResource
{
public int Id { get; set; }
public double Value { get; set; }
}
控制器:
public class MainController : Controller
{
private readonly IMapper mapper;
private readonly IMainRepository mainRepository;
private readonly IUnitOfWork unitOfWork;
public MainController(IMapper mapper, IMainRepository mainRepository, IUnitOfWork unitOfWork)
{
this.mapper = mapper;
this.mainRepository = mainRepository;
this.unitOfWork = unitOfWork;
}
[HttpPut("{id}")]
public async Task<IActionResult> UpdateMain(int id, [FromBody] MainObjectResource mainObjectResource)
{
MainObject mainObject = await mainRepository.GetMain(id);
mapper.Map<MainObjectResource, MainObject>(mainObjectResource, mainObjectResource);
await unitOfWork.CompleteAsync();
return Ok();
}
}
函数式编程
MM们
翻阅古今
相关分类