Search code examples
c#asp.net-core.net-coremodeldto

Best data type to use to map JSON arrays to DTOs in C# / ASP .Net Core


This is probably a dumb question, but I was wondering the following: I have a .Net 5 Web API, and in it I want to create a DTO to accept a POST request from a front end. The body in the POST request contains the following JSON:

{
    "aComment": "This is a text field",
    "aNumber": 5,
    "anArray": [1, 2, 3, 4, 5]
}

In the controller, I have an action method that will receive this request and map it into a DTO ("SomeDto"):

[HttpPost]
public async Task<ActionResult<SomeDto>> Post()
{
    // Some code
}

What would be the best data type to use in DTO for that JSON integer array?

* int[]

* ICollection<int>

* IEnumerable<int>

* List<int>

I'm leaning towards ICollection or IEnumerable becuase they are lighter than List. But I suppose int[] could also work nicely?

EDIT:

I see that .Net Core, when scaffolding an existing database, creates collections of type ICollection, and initializes them in the class constructor. Example:

public class SomeModel
{
    public SomeModel()
    {
        Accounts = new HashSet<Account>();
    }

    public int? Id { get; set; }
    public virtual ICollection<Account> Accounts { get; set; }
}

So maybe I should also use ICollection? Although in the scaffolded example above, the collection is of type "Account" (i.e. an object). Not sure if that would also be a good fit a simple collection of a primitive type such as Integer?


Solution

  • Use dynamic here

    public async Task<ActionResult<dynamic>> Post()