EFCore: don't require primary key for POST
Howdy, forgive me if I don't have the terminology down yet, I just started following this guide recently: https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-web-api?view=aspnetcore-8.0&preserve-view=true&tabs=visual-studio
So I've created a Model:
And here's my code for the Controller. Note that I am assigning the primary key within this method.
My problem is that I do not want the primary key (Guid) to be required in the request body to send the POST request. Is there any way around this?
I just want my POST request body to look like the following example:
Omitting the Guid from this results in the following error:
"JSON deserialization for type 'api.Models.User' was missing required properties, including the following: guid"
7 Replies
have users send a different class
Thanks @Tvde1 , I didn't realize how the models could be used, this solved my issue!
it's very good practicec to have separate models for input + output of your API, and your entity
so that changing one doesn't mean you have to change the other
I also like to be in the habit of making my "Read" models inherit from my "Write" models, with the extra fields on the "read" model representing the "readonly" values.
That way if you "read" out a model to fill out a form, when they post it back the fields should implicitly map 1:1 cuz, well, its the same fields!
yes! I have some where:
Where the PUT update endpoint uses te modification model, the POST create endpoint uses the creation model, and they return the User model with all properties
is works nicely with libraries like Mapperly, that make mapping easier/safer
but that's optional
oh wow thats pretty smart
I typically use a single "write" model, and the trick is I actually handle the id as a totally seperate variable, because when you follow proper RESTful design, the Id should come from the route instead of the body.
IE
Thats the pattern I typically adhere to for all my methods
And then you'll notice that you can have "Create" on a POST method without the Id, and the "Put" method does have the Id, and you can use the same model for both
If you wanna see some expanded examples of this pattern (I dont have txns setup yet on it but it gives the general idea) I have this controller as an example here:
https://github.com/SteffenBlake/Notes/blob/main/src/Notes.Website/Controllers/ProjectsController.cs