I have a model with some properties, one of which is a User:
public int UserId { get; set; }
[ForeignKey("UserId")]
public UserProfileModel User { get; set; }
And I have some JSON I'm posting up from the browser to a controller action:
[HttpPost("Add")]
public IActionResult Add(MyModel data) //<-- can't get this populated
{
MyModel model = _service.Add(data);
return Ok(model);
}
It works great! Except... it immediately errors out, because User is a required field. I am passing the UserId up. If I remove the User field from the model it works.
For context, this is part of a larger application framework with this sort of pattern.
I know I could create a separate Data Transfer Object and map it over to the original Model but that is a lot of extra code and manual configuration for this scenario.
Is there a way to get the Controller action and/or EF Core to somehow instantiate the object and just not be concerned with the User property?
Am I way overthinking this and I should just make User nullable, keeping UserId as the required field?
Example payload:
{
"title": "Test",
"content": "Lorem Ipsum Etc",
"userId": 1,
"comments": [],
"topicsIds": [
29,
30
],
"topics": []
}