I have a model with a List<string>. I am writing an API endpoint which accepts a JsonPatchDocument and uses that to update the List. The endpoint then saves the changes to the database. Logging shows me that the Json representation of the model is indeed patched, but saving to the db does nothing.
This is my model:
public class Music
{
public int Id {get; set;}
public List<string> Types {get;set;}
}
The database table does not allow List or arrays as a column type so I mapped it to a comma separated string like this:
modelBuilder.Entity<Music>().HasKey(x => x.Id);
modelBuilder.Entity<Music>()
.Property(x => x.Types)
.HasConversion(
x => string.Join(',', x),
x => x.Split(',', StringSplitOptions.RemoveEmptyEntries).ToList());
My endpoint:
[HttpPatch("{id}")]
public async Task<IActionResult> EditAsync([FromRoute] long id, [FromBody] JsonPatchDocument<Music> patchDoc)
{
var persisted = await Db.Music.FindAsync(id);
if (persisted is null) return NotFound();
patchDoc.ApplyTo(persisted, ModelState);
if (ModelState.TryGetValue(nameof(Music), out var modelStateEntry))
{
foreach (var error in modelStateEntry.Errors)
Logger.LogError(error.ErrorMessage);
return BadRequest(modelStateEntry.Errors);
}
await Db.SaveChangesAsync();
return new ObjectResult(persisted);
}
Logging shows me the original persisted:
{
"id": 1,
"types" : [
"One",
"Two",
"Three"
]
}
and after ApplyTo() has been called, the JSON has been correctly updated to:
{
"id": 1,
"types" : [
"One",
"Two",
"Test"
]
}
However the database entity remains unchanged:
SaveChanges completed for 'OperationsDbContext' with 0 entities written to the database.
I needed to add
just before the SaveChanges();