Steven
Steven

Reputation: 18859

Patching an object with an array of objects

I have a many-to-many relationship between Courses and Students for a school. Here's is what I have for a Course:

public class Course
{
    public Guid CourseId { get; set; }
    public string Name { get; set; }

    public ICollection<CourseStudent> Students { get; set; }
}

public class CourseStudent
{
    public Guid CourseId { get; set; }        
    public Guid StudentId { get; set; }
}

I'm using JsonPatch to PATCH my objects. I'm trying to add to the collection of Students, just to the end of the collection with this:

[
  {
    "op": "add",
    "path": "/Students/-",
    "value": [
       { 
         "CourseId": "07264DC9-9FEB-42E2-B1EF-08D58F58C873", 
         "StudentId": "FB6E6988-4A56-4CA4-86E2-E23090FAD98F"
       }
     ]
  }
]

But when I submit this, I get an exception saying:

"ClassName": "Microsoft.AspNetCore.JsonPatch.Exceptions.JsonPatchException",

"Message": "The value '[\r\n {\r\n \"CourseId\": \"07264DC9-9FEB-42E2-B1EF-08D58F58C873\",\r\n \"StudentId\": \"FB6E6988-4A56-4CA4-86E2-E23090FAD98F\"\r\n }\r\n]' is invalid for target location.",

The structure looks correct to me based on the Json Patch docs. Any idea why it won't accept my format?

Upvotes: 5

Views: 3186

Answers (1)

Steven
Steven

Reputation: 18859

Ended up figuring it out, the format should be:

[
  {
    "op": "add",
    "path": "/Students/-",
    "value":
       { 
         "CourseId": "07264DC9-9FEB-42E2-B1EF-08D58F58C873", 
         "StudentId": "FB6E6988-4A56-4CA4-86E2-E23090FAD98F"
       }
  }
]

Upvotes: 2

Related Questions