I have a Job class with many JobBudgetItems. I am implementing a PATCH method on the controller using Microsoft's built-in JsonPatch library. The issue I'm having is when I try to update a field in a JobBudgetItem, EF Core doesn't persist the change. Instead it creates duplicates of each existing JobBudgetItem with a different Id.
Job
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 /Job/1
{
"id": 1,
"name": "Test",
"jobBudgetItems": [
{
"id": 1,
"category": "ATestCategory",
},
{
"id": 12,
"category": "BTestCategory",
}
]
}
PATCH /Job/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));
}
Repo
public async Task<IDataOperationResult> UpdateJobAsync(Job job) {
_context.Jobs.Update(job);
try {
await _context.SaveChangesAsync();
return new OperationResult(true);
} catch {
return new OperationResult(false);
}
}
How can I make an update to a JobBudgetItem persist in the database?
UpdateJobAsyncmethod, notCreateJobAsyncjobUpdateDtoback tojobFromRepo, does yourjobFromRepostill have it's id? Could it be that it was nulled by the map and therefore ef creates a new object?