C
C#2y ago
Marmot

❔ Serialization Posting Issues

I am having an issue where my Model has a virtual collection in it, however when creating a new entry it is failing because it is expecting that collection which is not present. Model
public class CustomerDTO
{
public Guid Id { get; set; }
[Required]
public string Name { get; set; }
public bool IsTestCustomer { get; set; }
public virtual ICollection<CustomerClientDTO> CustomerClients { get; set; }
}
public class CustomerDTO
{
public Guid Id { get; set; }
[Required]
public string Name { get; set; }
public bool IsTestCustomer { get; set; }
public virtual ICollection<CustomerClientDTO> CustomerClients { get; set; }
}
Service
var settings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
MissingMemberHandling = MissingMemberHandling.Ignore
};
var content = JsonConvert.SerializeObject(customer,settings);
var bodyContent = new StringContent(content, Encoding.UTF8, "application/json");
var response = await _httpClient.PostAsync("api/customer", bodyContent);

}
var settings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
MissingMemberHandling = MissingMemberHandling.Ignore
};
var content = JsonConvert.SerializeObject(customer,settings);
var bodyContent = new StringContent(content, Encoding.UTF8, "application/json");
var response = await _httpClient.PostAsync("api/customer", bodyContent);

}
Now it is failing because the Controller is expecting
{
"id": "3fa85f64-5717-4562-b3fc-2c963f66afb6",
"name": "ass",
"isTestCustomer": true,
"customerClients": []
}
{
"id": "3fa85f64-5717-4562-b3fc-2c963f66afb6",
"name": "ass",
"isTestCustomer": true,
"customerClients": []
}
but it is only getting
{
"id": "3fa85f64-5717-4562-b3fc-2c963f66afb6",
"name": "ass",
"isTestCustomer": true
}
{
"id": "3fa85f64-5717-4562-b3fc-2c963f66afb6",
"name": "ass",
"isTestCustomer": true
}
I cant seem to find a google result for this
2 Replies
Marmot
Marmot2y ago
NM. I got it needed to nullable the collection.
public virtual ICollection<CustomerClientDTO> CustomerClients { get; set; }
public virtual ICollection<CustomerClientDTO> CustomerClients { get; set; }
and change to
public virtual ICollection<CustomerClientDTO>? CustomerClients { get; set; }
public virtual ICollection<CustomerClientDTO>? CustomerClients { get; set; }
Accord
Accord2y ago
Looks like nothing has happened here. I will mark this as stale and this post will be archived until there is new activity.