I have 2 models in my MVC project.
Assignment:
public class Assignment
{
public int ID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public User User { get; set; }
}
User:
public class User
{
public int ID { get; set; }
public string Name { get; set; }
public ICollection<Assignment> Assignments { get; set; }
}
There is a relation "Many to One" between them. One User can have multiple Assignments. Currently I'm working on API Controller and I want to implement an updating method for assigment to be added for particular user.
What I've find out so far is to try out with PATCH method. Here is my code block that isn't working how I want it to.
[HttpPatch]
[Route("api/[controller]/{id}")]
public IActionResult DelegateAssignment(int id, [FromBody]JsonPatchDocument<Assignment> assignmentPatch)
{
var assignment = _context.Assignments.Find(id);
assignmentPatch.ApplyTo(assignment);
_context.SaveChangesAsync();
return Ok(assignment);
}
And the Body im sending through API (testing using Postman):
[
{
"op": "replace",
"path": "/User",
"value": {
"id": 1,
"name": "User1"
}
}
]
However my database is not updating at all. So my question is - what is best way of updating one database table related to the other one (related objects), so both models gets updated (the Assigment will get proper User and the User will have a new item added to Assigments collection). I was thinking also about implementing POST method, but I dont know which version would be the best as a solution. Thanks for helping me out! :)