'Instantiation of class in controller action not mapping post data for array of ints
Using EF Core, C# .net 6 generic API setup, client is SPA.
I'm trying to instantiate some post data into a strongly-typed object:
public IActionResult Submit(MyModel model)
What the client sends:
gameIds: [9, 8, 7, 18, 17, 6, 5, 14, 12]
What the server gets (inspecting generic received object):
{[gameIds, {[9,8,7,18,17,6,5,14,12]}]}
In the populated model:
GameIds Count = 0 System.Collections.Generic.List<int>
All of my other properties automatically map correctly: ints, strings, etc.
I have a bit of an odd setup (to me anyhow) trying to get a list of Ids from a many-many foreign entity relationship when available, or just storing a List<int> for use in the service saving this off when it's a new record.
The model class itself:
private List<int> _gameIds;
[NotMapped]
public List<int> GameIds {
get { return (_gameIds?.Count == 0 ? Games?.Select(x => x.Id)?.ToList() : _gameIds) ?? new List<int>(); }
set { _gameIds = value; }
}
public List<GameModel> Games { get; set; }
I'm not sure if my GameIds declaration is messing things up, or if it's something I'm missing in the instantiation, or if my approach is just wrong in general.
Solution 1:[1]
If you review in details your get part of property, written in a less compact form:
List<int> list = null;
if (_gameIds != null && _gameIds.Count == 0)
list = Games?.Select(x => x.Id)?.ToList();
else
list = _gameIds;
return list ?? new List<int>();
In case in which _gameIds == null, you return the else part, that is null, and return a new empty list. I prefer don't compact a lot because is more readable:
get
{
var list = _gameIds != null && _gameIds.Count == 0 ?
Games?.Select(x => x.Id)?.ToList() :
_gameIds;
return list ?? new List<int>();
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Victor |
