我有很多Job
的JobBudgetItem
类。我正在使用Microsoft内置的JsonPatch库在控制器上实现PATCH方法。我遇到的问题是,当我尝试更新JobBudgetItem
中的字段时,EF Core无法保留更改。相反,它使用不同的ID创建每个现有JobBudgetItem
的副本。
工作
public int Id { get; set; }
public string Name { get; set; }
public IEnumerable<JobBudgetItem> JobBudgetItems { get; set; }
JobBudgetItem
public int Id { get; set; }
public string Category { get; set; }
public int JobId { get; set; }
public Job job { get; set; }
GET /工作/ 1
{
"id": 1,
"name": "Test",
"jobBudgetItems": [
{
"id": 1,
"category": "ATestCategory",
},
{
"id": 12,
"category": "BTestCategory",
}
]
}
补丁/作业/ 1
[{
"op": "replace", "path": "/jobBudgetItems/0/category", "value": "CTestCategory"
}]
JobsController
[HttpPatch("{id}")]
public async Task<IActionResult> PartiallyUpdateJob(int id, [FromBody] JsonPatchDocument<JobDTO> patchJob)
{
var jobFromRepo = await _jobManager.GetJobAsync(id);
var jobUpdateDto = _mapper.Map<JobDTO>(jobFromRepo);
patchJob.ApplyTo(jobUpdateDto);
_mapper.Map(jobUpdateDto, jobFromRepo);
await _jobManager.UpdateJobAsync(jobFromRepo);
return Ok(_mapper.Map<JobDTO>(jobUpdateDto));
}
回购
public async Task<IDataOperationResult> UpdateJobAsync(Job job) {
_context.Jobs.Update(job);
try {
await _context.SaveChangesAsync();
return new OperationResult(true);
} catch {
return new OperationResult(false);
}
}
我如何对JobBudgetItem进行更新,使其持久存在数据库中?
最佳答案
事实证明,我对AutoMapper的实现是成功的关键。我选择忽略我的JobBudgetItemDto
(子记录)上的ID,这又导致原始ID在保存回数据库之前被映射回时消失。
CreateMap<JobBudgetItem, JobBudgetItemDTO>()
.ReverseMap();
//.ForMember(x => x.Id, opt => opt.Ignore()) // Removed this line.