Click here to Skip to main content
15,885,244 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
The code is only an example, not a production code, as simple as can be to show the issue. The issue is the collection is null if controller receives null MyItems collection.

Models:

C#
public class PBS
    {
        public PBS()
        {
            MyItems = new List<int>();
        }


        public ICollection<int> MyItems { get; set; }
    }

public class Command : PBS
{
    public int Id { get; set; }
}


Controller:

C#
public async Task<IActionResult> CreateCommandAsync([FromBody] Command command)
{
    await Mediator.Send(command); //Mediator only calls handler based on command type
}


What I have tried:

So the question is why when I send JSON to controller with MyItems = null then the MyItems collection is null instead of empty? Shouldn't constructor just turn it into an empty List? What am I doing here wrong? It's REST WebAPI Core 2.2
Posted
Updated 5-Nov-19 10:24am
Comments
Kornfeld Eliyahu Peter 29-Oct-19 5:41am    
It is about order...
The initialization in the constructor is prior to the set of the property, and that overrides the previous value with null...
You may write some code in the property setter to handle the special case of null...
[no name] 29-Oct-19 10:23am    
Ok, I get it. So the only solution here is to implement setter explicitly and initialize empty collection when null?

Hello,
you could also do it like below
C#
public ICollection<int> MyItems { get; set; } = new ICollection<int>() 

you don't need any ctor / setter in this case
 
Share this answer
 
Comments
Richard Deeming 5-Nov-19 16:14pm    
That won't fix the OP's problem. If you deserialize a JSON representation of that class with the MyItems property set to null, it will overwrite the value set in the property initializer.
If you're using JSON.NET, try making the property read-only:
C#
public class PBS
{
    public ICollection<int> MyItems { get; } = new List<int>();
}
JSON.NET handles that correctly:
  • {}{"MyItems":[]};
  • {"MyItems":null}{"MyItems":[]};
  • {"MyItems":[1,2,3]}{"MyItems":[1,2,3]};

NB: Unfortunately, the new System.Text.Json APIs[^] can't currently cope with this - the MyItems collection will always be empty. There is a proposal to add a new attribute[^] to work around the problem.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900