I am trying to deserialize the following json to an object and get an error when my object has a collection of child objects.
My json:
{"@odata.context":"http://localhost:5281/odata/$metadata#Agents(Notes())","@odata.count":1,"value":[{"AgentNumber":"0123","EndDate":"2025-01-01","Name":"TestAgent","StartDate":"2024-01-01","CreatedBy":"JWS","Id":3,"IsActive":true,"UpdatedBy":null,"Notes":[{"Author":"JWS","Content":"Bacon ipsum dolor ","CreatedBy":"JWS Seed Test","Id":9,"IsActive":true,"UpdatedBy":null},{"Author":"BOB","Content":"Bacon ipsum dolor amet biltong shankle pork pork loin tongue short ribs. ","CreatedBy":"JWS Seed Test","Id":10,"IsActive":true,"UpdatedBy":null}]}]}
This is being deserialized into the following class:
public class ODataAgentResponse{
[System.Text.Json.Serialization.JsonPropertyName("value")]
public List<Agent>? Agents { get; set; }
[System.Text.Json.Serialization.JsonPropertyName("@odata.count")]
public int Total { get; set; }
}
The Agent class is:
public class Agent
{
public string AgentNumber { get; set; }
public string Name { get; set; }
public ICollection<Note> Notes { get; set; } = new List<Note>();
}
The Note class is:
public class Note
{
[MaxLength(50)]
[Required]
public required string Author { get; set; }
[Required]
public required string Content { get; set; }
}
If I don’t include the “Notes” data in the json everything deserializes properly. If I include the “Notes” data I get the following error:
"An item could not be added to the collection.
When items in a DataServiceCollection are tracked by the DataServiceContext,
new items cannot be added before items have been loaded into the collection."
Any ideas what on how to fix this? This only happens when there are child collections. if there is a child object it works fine.