❔ C# WebAPI - how to make a field 'optional' ?
I'm creating some WebAPI, I'm starting from a get, for the retrieval of users from a DB.
I'm using .NET 7.0 and EntityFramework.
The form that make the search request can take in input those fields:
All fields must be optional, obviously at least 1 should be sent.
I wrote some code:
As I understood, in that way EF understand how should it works, and the statement should works without bugs.
I think I'll only have to add a check at the beginning, for make sure that at least 1 field is sent.
Anyway when I test the API and I put only 1 field, for example
I suppose that's why I never declared anywhere when the parameter is optional, and when not, since I just defined the code that have to be executed after a correct request is sent.
Browsing on the web I found some guides that suggest to add
Other guides suggest to set all parameters to
I'm using .NET 7.0 and EntityFramework.
The form that make the search request can take in input those fields:
Database ID User ID FromDate ToDate UsernameAll fields must be optional, obviously at least 1 should be sent.
I wrote some code:
As I understood, in that way EF understand how should it works, and the statement should works without bugs.
I think I'll only have to add a check at the beginning, for make sure that at least 1 field is sent.
Anyway when I test the API and I put only 1 field, for example
dbId I get Error 400 as response, The username field is requiredI suppose that's why I never declared anywhere when the parameter is optional, and when not, since I just defined the code that have to be executed after a correct request is sent.
Browsing on the web I found some guides that suggest to add
[Required] tag on mandatory fields, inside the model.cs making the rest being optional, but this seems not working.Other guides suggest to set all parameters to
null by default, or at least setting the FrontEnd to work in this way.