ASP.NET Core Web API CRUD With Entity Framework - Full Course ⭐ [.NET6 API]

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
do you want to learn how to build an asp.net core web api from scratch in this video i will go step by step and create a brand new asp.net core web api using dot net 6 and i will use entity framework core to first create our api with an in-memory database and then i will show you how easy it is to switch implementation to a sql server database please watch this video right till the end so that you don't miss any details in between if you like this video please hit that like button and comment with a heart emoji also subscribe to the channel so that you don't miss my next upload with that said let's create a web api using asp.net core i have created a folder for myself in which i will create the asp.net core web api after that i will open visual studio 2022 and i will click on create a new project from this list i will select asp.net core web api and click next and in here i will specify a name for the project and solution and i will also give the location of the folder [Music] after that click next and choose a framework we are on dotnet six which is the latest or as of the time of the recording of this video so i will choose that and i will select all the default options and click on create visual studio has created a an asp.net core web project for us and inside here we can see only one controller and there's a class file supporting that controller we also have a program file in which uh which is the starting point of our application as you can see we have some services which are injected to it and we are building the service over here and after that we have the http request pipeline and then finally we run our application over here let's first try to run our application and see what we get out of the box you can run your application through this contacts api button or you can run it without debugging so i'll use this button for now when our application is running you can see the swagger ui documentation and inside here you can see all the apis uh that you have created inside your application and this is the weather forecast controller that was given to us by default from the visual studio and inside here we get all the methods that are defined for that api endpoint for example we only have the get endpoint for the weather forecast so if i expand this get endpoint and if i click on try it out you can actually use this documentation to make http calls to call our database in this case this is a static file which is if we go back to the code and if we open the controller we have the static list of uh of weather forecast which is coming from this file as well which is a static file it's not talking to our database at the moment but it's still returning some values so if we click on execute we find that we are getting the list of the the weather forecast values back to us this is great we have some documentation out of the box and we also have a default controller but what if we want to add our own controller and endpoints in the next few minutes we will do that we will create a controller and we will create a static implementation of a database so we will not use a database directly but we will understand how we can use in memory database and we will first call that and after that once we are comfortable doing that we will actually use entity framework core to create a new database and then we will save and fetch values from that we have come back to our application and the first thing we will do is to install the in-memory package and we will install this from the nuget package manager library and to do that i will come over here to dependencies i will right click on that and i will click on manage nuget packages in here i will search for this package which is microsoft dot entity framework code dot in memory i will copy and paste that i will click on it and install the latest version the package has now been installed it is now time to create some domain models for our contacts api asp.net core web api so i will come over here and in the solution i will create a new folder i will right click on that add a new folder and i will call this models [Music] inside the models i will create a class so i will click on add a class and i will call this contact [Music] this will be our contact domain model and inside that i will have a few properties the first property i will have is a grid of id and after that i will have a string of full name which will have the contacts full name after that i will have an email address for the contact and that will be of type string as well and then i will have a phone number which is for the contact which will be of type long and finally i will have a property of address which will store the physical address of the contact and that will be of type string now we have the contacts domain model and we also have installed the in-memory database package from nuget it's now time to create a class file which will talk to our database which will act like a domain access layer because we are using entity framework core we use the concept of db context which acts as a class that talks to the database no matter what type it is and it also fetches and retrieves data for us so let's create a db context i will click on solution add a new folder i will call it data and inside data i will create a new class file i will call this the contacts api which is the api name and followed by the word db context so contacts api [Music] db context inside the class this class will actually inherit from the class db context click control dot to import the dependencies this is using microsoft dot entity framework core which got installed when we installed the in-memory database package after that we have to create a constructor i will put control dot over here and i will use this generate constructor which to which we are passing the options and the options are being passed to the base class after that in the db context we have to create properties which will act as tables for entity framework core so i will create a property over here and because we only need one property which is our contacts model and we only want to retrieve uh update delete and add contacts so i will have a dbset property of type contact i will import this contact from models and i will call my property contacts it's now time to inject this contacts api db context into the services of the solution and we will use dependency injection later on to inject that injected service into our controller so that we can talk to our database i will come over here into the program.cs file and right below this line where i am injecting the service for swagger i will use the builder.services and i will write add db context because i want to add the db context and i will give the type of it which is the contacts api db context click control dot and import the using statements so this is coming from contacts api.data the one we created and after that i will give some options to it i will tell it to use the in memory database so i will say use in memory database and over here if you do control dot you can use this package microsoft.net framework core which gives you that option to use the in-memory database after that we have to give the database name so in strings i can give the database name which can be contacts db and finally i will close my brackets [Music] now we have given entity framework core everything it needs to create an memory database and it also knows about the tables because we have given it a db set as well now it's time to create a controller for ourselves and inject this db context so that we can read and write from this in memory database so i will come to controllers right click and add to create a new one i will use the mvc controller empty click on add and i will give it a name of contacts so this will be our contacts controller.cs first of all i will annotate my controller with the keyword api controller telling that this is an api controller and not an mvc controller and after that i will give a route to my controller and the route of the controller would have again in strings let's say going to api slash the controller name which is contacts [Music] and another way to give contacts because that's the same name as we have of the controller is to give it in brackets like that and specify the word controller [Music] this is acting the same as the one we had before which is slash contacts but this time it is taking the controller name which is contacts over here and injecting it over here in the route so this is acting the same way as we had over here as contacts so now that we have defined the data annotations for our controller it's now time to create our first method which is the get method so i will edit the auto generated method over here which is index so i will call this get or you can call it get contacts you can also call it get all contacts and this is of type this is returning an i action result that's fine we will annotate this method with the http get keyword [Music] by default asp.net core is automatically identifying this as a gate method but for us to use swagger ui because we use the documentation which is in open api documentation we have to annotate this with the http get keyword as well so we have created this method now we want to inject the the db context because we want to talk to our in-memory database so i will come over here and i will create a constructor the short form is ctor and tab tab in here i will inject the db context and the name of our db context is contacts api dp context [Music] so i will write contacts api [Music] control dot and i will use this from here and i will call this db context and i want to create a private property so i will put control dot and use the same name so now i can use this private read-only field db context to talk to my in-memory database and in here i will come over here and i will use this db context field to put a dot to say talk to the contacts table because we have given the db set property inside the context and it knows that contacts is a table in our database so i will talk to the contacts table and return a list [Music] and i can directly call the return keyword over here and i don't need the second line if you look at it it says that we cannot implicitly convert the type generic list to an i action result so either you have to wrap it inside an ok statement to give it a 200 response because this is a restful api or you can give an eye enumerable over here like we had in the weather forecast api so it was in uh it was an i enumerable of the type so we can pass in iron numerable of the domain model but i want to give it uh the i action result so i will wrap this inside an ok response [Music] so that looks good it's now time to run our api to see if everything is working we don't have anything in the in memory database so it's it'll return uh an empty list but later on we will define methods for adding a new contact and uh and other stuff so i will run this application as you can see here now along with the weather forecast api we are also getting the contacts api and inside that we have one get method if i expand on that and click on try it out i can click on the execute button and this is trying to talk to our in-memory database and trying to fetch all the contacts for us and you can see the response is 200 in a restful world 200 means a success response and you can see an empty array because we don't have anything in the in memory database this is returning an empty list so it looks like this is working but we'll come to know more when we add a new contact inside that and then we try to retrieve those all contacts coming back to our application it is now time to implement the add contact functionality so i will create a method first which will be public i action result and i will call my method add contact and this will have the keyword the http verb of http post because when we add a new contact or when we add a new resource we use the http post verb in here we will first have to get some values from the user so i will use another model and i will create a request model so i will create a class and i will call this add contact request [Music] so we have created another model because we want to get only certain fields from uh and we want to store it in the database and if you look at it here we have five fields in total but we don't want to get the id from the user we want to give it our own id so i will copy these four fields and i will paste it inside the add contact request because i want the user to only specify these four fields and i will give the id myself inside the api in here because you have created the new request object i will use that i will import it from contacts api dot models and i will give it a name using this i will create the contact object so i will first create a new contact object so a variable of contact is equal to new contact and inside here the first thing i'll do is i will give it an id and that will be a new id so i will use good dot new good and after that i will use the objects coming in from the request so address would be add contacts uh add contact request dot address and after that we will have the email which will again be coming from that and we have the full name which is coming from the request object and then we have the phone which is coming from request object dot phone so here we are doing our mapping between the add contact request and the contact domain model and this is what goes inside the database so that's why we have created that and now we can talk to our db context or our database using the db context and store this new contact so i will come over here and i will use the db context to talk to our table and the table name is called contacts [Music] and after that i will use the add method and the add method takes the contact uh model you can see it over here and i have the contact model so i can copy that and paste it over here [Music] i can also use the add async method so if i use async but because i'm using the async keyword i can i have to use the await over here and because i'm awaiting on a method i have to declare this as an async method so now we are adding this object in the database and with entity framework core you also have to save the changes to the database before you can actually see the changes so i will use await db context dot save changes async so now our method becomes an async method now finally when we have added our our resource to the database and we have saved the changes it's now time to return the request so we will use the return word with an ok response [Music] and i will send the request that we created which is the contact wrapped inside an ok response and if you come over here it's it's complaining about something it's saying it's not a type of task of type something because you're using an async keyword the i action result has to be wrapped inside a task [Music] and that makes our method asynchronous we can do the same thing over here as well so i can use the async keyword use the task and wrap the i action result in it and because we are using an async method we have to use uh we can talk to the database asynchronously and here i will use the keyword to list async and i will use control dot to import this using statement and because we are using an um an async thing we are we have to use the await keyword over here [Music] so this makes both our method asynchronous now we have the add functionality it's time to test it using swagger so i will run my application on running my application i can see another method being created inside the contacts endpoint i have the post method which is going to api slash contacts and if i expand on that click on try it out i now have a request that i can send in so i'll send in some details from here in adjacent object and that will get mapped to the add request object that we created and it will try to store it in the database so i will first populate this so i have created a json respon request and i'll paste it over here to save some time and this is just example values over here and now that that's filled we have filled our four properties we want to send and save it to the database i will click on execute and as you can see we got a 200 response back which we know is a success response and the response body was the same that we sent along with the newly created id for that contact so now that we can see it's a success response we can also try to go to our contacts api to get all the contacts and previously where we were getting zero contacts back if we try it out now we should get one back so you can see it's a 200 response and the array which was empty before has now one contact keep in mind that because this is an in-memory database the moment we close our application here the memory would be cleaned up and the database would have zero results back so as long as the application is running you could you would have results uh populated in it but once you close your application and restart your application you would see uh the default in it which is no contacts in our database back in our application it's now time to implement the update contact method and we will come over here and create a new method for it so public async task of type action result [Music] and we will call this method update contact and the update contact method because it's an update we will use the http verb put for it and we also want to define a route because it cannot go to the same route the route for this one will have uh the work the keyword id in it because we want to take the id of the contact that we are trying to update from the route so in here inside the string i will use curly braces and i will specify the word id and i it will be of type good because we are using ids of type grid in our model as you can see over here and because it's a type of code i can make it a type safe by using the word good in here and because this is coming from the route the first parameter our method will take is the id which will be from route [Music] and it's of type good [Music] as we know and the name of the parameter would be the same name as it's here as it's coming from the route so if you have defined a different name over here it has to match the name over here so i will define it id because i've defined it in the route and now that we have the id for the contact we also want to know the updated fields so similar to what we had over here i will create a new request object i will create a class and i will call this update contact request this will have all the properties we want to update for that contact so if you look at the contacts model again we have five properties and we'll ask this question that do we want to update the id of this property of this contact and the answer is no but do we want to update all the other properties to which the answer may or may not be yes in my case it's yes so i will copy all of these four and paste it inside this update contract request now the question may arise that because update contact request is similar to add contact request why are we not using that because the name is totally different the use case could be totally different and we are achieving a separation by doing that so we create different uh request objects for every call and we can now use this request object which is update contact request [Music] and i will use the name of it as well [Music] and finally now it's time to implement the method i will first use this and i will first actually try to check if our database has this value to update or not if it doesn't have it i will return a not found back so i will first use i will try to go to the database so db context dot table which is contacts dot find i will use the find word and the find takes an object or key values so i can use the id over here and because the id is a primary key a unique identifier it will trying to it will try to find that id in our database no matter what it is it's an in-memory or a sql server database so it will try to find that id in there and if it finds it it will return it to me so i will i can use where contact is equal to that and if the contact exists we will try to update it if it doesn't exist we will return a not found back so i'll so first check if contact is not equal to null that means it exists we will do some more stuff here but otherwise return uh not found back and this tells the the user or the client that we were not able to find this id so that so we can't proceed further to update uh this contact in here if we found the contact we will use this request to first form our contact request and then we will update the um [Music] the contact the existing contact so we are believing that this contact was found with the id of this so it's now time to update the properties so i will use this contact and i will update the properties that i want to update so full name would be coming from the request contact dot address will be coming in from the request after that i will update the the phone and finally we have contact dot [Music] email is equal to the request dot email so we have updated the full four properties and it is being tracked by entity framework core so all we have to now do is save these changes back so i will use db context again and as we used the save changes in here we will call save changes async and i will use the await keyword [Music] let's try to see if the find also have a find async which it does so i will use the await keyword over here and now our method becomes asynchronous after i have saved these changes i want to return the response back so i will use the return keyword and it will be of type okay meaning a success response and i can now return the updated response back so i can return the updated contact pack so that's done and it's now time to test it we can see our update method over here and let's expand on it and click on try it out it needs an id and it needs a request object which we want to update but we don't have an id because if we come back to the get all contacts click on try it out as i told you before because we have restarted the application our employees sorry our contacts list have been uh cleared out and we want to first create a contact before we are able to update it so i will use the same request again and i will come to the add method click on try it out paste it and execute it this has created one contact for us i can minimize that now and if i execute get all contacts you can see one contact being created so now i can come to the update and i can use this existing contact so i have to first copy the id and paste it over here and if i don't do that if you see here it's a required field and if you click on it it throws an error because it needs a valid good so i will paste it over here and then just to save my time i will also copy this object and paste it over here now the update request object doesn't have an id so i will first clean that [Music] and now we can play around with the values these are existing values but let's say we wanted to change something so the address has been changed from one some street to to some street and then the phone number also changed [Music] and because we have made some changes if we try to execute and update our contact list let's see what happens so i'll click on execute [Music] we can see a 200 being returned back and the updated response which has our changes but just to confirm that the changes are in the database we will come back to our get all contacts and click on execute we can see in the get request the details of that contact have been changed and these values are coming from our in-memory database so we can say that our put operation or the update operation is now working fine so it's now time to create the delete operation and also we want to uh we want to implement the get operation for getting a single contact back based on an id so let's create these two methods and then test them together let's first create the get single contact because that's an easy one so to get a single contact i will place it along with the gate operation to get all the contacts i will first create a method public async task of type i action result and i will call this get contact without the word s because it's a single contact and i will annotate this with the http get keyword [Music] and i will also give it a route because we want to take the id of that single contact that the user wants to search on so i will create a route and the route will be similar to what we had in the update so i can copy paste that but to explain it takes an id in the route and because we are taking something from the route i'll use the from route keyword and i will use the type of it which is good and the name which is id so this should match again the one coming from the route so that it can map the values from it now an id is coming back as we did something in the update contact we've tried to find the id from the database and then we returned the result we will do something similar over here so we can actually copy this line and paste it over here what it's trying to do is it's trying to talk to the database and the contacts table to find the id to find a resource with the primary key of this id and if we get one we'll return it if we don't get one we will return a not found back so this could be as simple as if contact is null then return not found and you can pass a message in the not found as well but i'm keeping it empty otherwise just return the found contact and this and return the found contact but we have to wrap it inside an ok response so now we are returning the request uh we are returning the contact uh back in in a 200 response uh based on the id that is being passed and we will test this along with our delete so let's first implement our delete and that will be again a public async method task of i action result the method name will be called delete contact [Music] and delete also if you think about it you want to delete a single contact right so you will use the delete keyword first so http delete and if you think about it you need an id to delete so i will use the same route again and because we are using the id from the route we have to use the we have to use the mapping over here in the parameter of this method so this is coming from the route it's of type good and the name is id which matches this one and if you want you can also remove this because asp.net core is smart enough to understand it's coming from the route but just for demonstration purposes i'm keeping it over here we'll do a similar thing of what we did inside the contacts so first we will go to our tb context we will talk to our contacts table and try to find a resource with the primary key of id store it in a variable and we will check if the contact was not null that means it was found then the request is to delete it so we will delete that object from the database so using db context again we use the remove method and we pass in the object or entity that we want to remove and in this case the entity is contact so i will pass contact in that remove method and this hasn't been completed yet because you have to save changes so i will use dbcontext.save changes i can use the save changes async and put the await keyword in front of it and if this contact was not found i will return a not found again and if this was successful for example the id was found the resource was found in the table we have removed it we have to return a response so we can return an ok response and you can pass in anything you want you can pass in this was deleted or this contact was deleted uh i am happy to pass the contact back in case the client wants to do something with it [Music] so we have implemented our get single method and delete as well so it's now time to test it so i'll run my application as we can see here now we have multiple methods inside our contacts api and the one that we want to test is the delete and the single get with the id but before we can proceed because we restarted our application we have to insert a record to be able to uh edit or delete it so i will use the same json again so i click on try it out paste that same json click on execute and that creates a new contact in the database i can minimize that and click on try it out which will give all the uh requests over here so let's say for example we wanted to have two results in here two contacts so i'll use the add method again and this time i'll change the name to my name and let's just update the email this is surely my real email and if i click on execute we have another success pack so the get all response should now have two objects and two contacts in our contacts api so first of all i will use i will demonstrate the get single contact back so i'll use my id with the name of you know my name and i will use the id of it to fetch details for a single contact which is this method over here and as you can see it takes an id inside the route of it and if i click on try it out paste the id and click on execute it gives you the result back and you can see it's my name and not the other contact and that seems to be working and finally if i wanted to delete this contact because we have the id copied i can click on here click on execute and as you can see it returned the 200 response with the deleted contact back and just for fun because we know it's deleted if we try to do it again we should get a 404 back which is not found if i click on execute again we find it that the application the api is saying we are unable to find this resource in the database so we have not deleted it so it's saying a 404 not found back so we can see that all our methods and implementations for the api endpoints are now working but all of this is is still using an in-memory database so whenever we close our application the database gets cleared and it's not really persisting anything so now we want to change our implementation from using an in-memory database to a sql server database and now we'll see how easy it is to switch providers once you have the base implementation in place i have started my application and now it's time to implement sql server database and try to store our values inside an actual sql server database so to do that we first have to install a few entity framework core packages and these are uh entity framework code dot sql server we will not install the first one because it got installed as part of the in memory database installation so we will first install the sql server i will come over here right click on dependencies click on manage nuget packages in the browse section i'll search for this package i will click on it and install then i will search on the next package which is entity framework code.tools and this is responsible for creating the database for us by using entity framework core migrations so i will click on it and install now that we have installed the packages it's now time to first create a connection string and we create connection strings inside the appsettings.json so i will come to this file and below the allowed hosts i will create a connection strings property and i will create a key and i will call this the db connection string name so contacts [Music] api connection string and the value for it will be server and i'll i have installed sql server on my machine and i'm using this server so if you if you can go online and search for how to install sql server and also i'm using microsoft sql server management studio to query my database so this is ssms so you have to do two installations to reach here and if i try to connect to it you can see the server name over here and this is just a local server so i will copy this so you have to copy the server name that you are using and if i refresh on this server you can see there's no database that's called contacts api db but we will create one soon so i'll come back and i will provide the server name that i copied so you have to replace this value with whatever server you are using after that i will mention the database as we saw we don't have a database but we want to create one and we want to create one using the name that i'm specifying now which is the contacts uh contactsdb [Music] you can mention your own name and after that we have to specify trusted connection is equal to true [Music] so trusted underscore connection is equal to true [Music] and with that it's now time to use this connection string and where we injected the in memory database so i'm coming back to the program.cs file we used this line which is the in memory database i will copy paste it one more time and comment the other one i will replace the in memory database with the sql server implementation so i will say use sql server and for sql server if we open the brackets it says that we can give it a connection string which is of type string and we have already defined the connection string in the app settings so we will take the value from here coming back i will use the builder.configuration to access that value so builder dot configuration and i will move this to the second line and i will put a dot to use this method get connection string and it takes a name which is the same name as we have over here which is the key so use the same name as you have defined in your app settings.json so i will come back to the program.cs file and specify this name inside a string and close the brackets and that's it we have replaced our in-memory implementation with actually using a sql server implementation and entity framework also has options to use a postgres database or a sql lite database so you can use whatever you want to like and after that we don't have to do anything we just have to create the the sql server database using migrations and to start migrations we come to tools and we go to nuget package manager and open package manager console in here we will type two commands the first command is add hyphen migration so i will copy that and paste it over here and after that i want to give the name of the migration in quotes so i can say because this was the first time i'm creating a database i can call it the initial migration [Music] and i will press enter and this is creating a migration for us meaning it's creating a class file with all the code required to create a new database and we will soon see that a migrations folder has been created over here if everything goes fine so you can see a new migration folder over here and inside that we have the initial migration class file and if you look at it it has two methods an up method and a down method if we expand the up method it has everything it needs from the db context file to create a new database and to create a new table with all the properties required so it's actually from a c-sharp world it's actually creating us a sql uh database and tables for us so i will come back to my package manager console and after that we will use the second command which is update hyphen database and with that i'll just press enter and update database which will actually run the migration so till now we hadn't had anything in our database naming you know called contacts api so i'll come back to the sql server and if i refresh on the server expand databases we have a contacts db now and if i expand on the tables the table name the only table name that we have inside our api is the contacts api and if i select star or select top thousand rows in there you should see zero values because we haven't inserted anything at the moment so you can see zero values in here but now let's use let's run this api and let's try to add new values to it and see if our api is still working with the sql server implementation i've run my api and as you can see we have these options that we can trigger first of all let's see if our api has got any contacts at all so if i click on try it out you can see it's taking more time because it's now making a connection to a sql server database and not an in memory database and you can see a 200 success response pack but it doesn't have any contacts in it so we will use the add method to first create a contact so i'll copy the value of the json and i will come to my post method and paste this value and we will try to create a new contact it came back with a success it also has given us an id and let's see if we are able to get those contacts now it was empty before if i click on execute it now comes back with a contact back and we believe that it's not using an in-memory database but it's using a sql server database this time and to confirm that i'll come back to my sql server we had zero rows returning but if i click on execute again we now can see the values are getting persisted inside the sql server database and we are no longer using uh the in-memory database that was great for our development purposes and you know we used that to do quick testing before any implementation was needed so now we will go ahead and test the other operations as well i'm pretty sure they will work but first of all i will create another object over here or another contact and click on execute now if we get execute again we have two records let's use the same testing i will use the id with my name in it and first of all i will try to update it or let's just delete it or let's get it first anything if i pass the id here click on execute it should get the id with my details in it as you can see so now we no longer require this id so let's delete me click on try it out pass the id click on execute and as you can see a 200 back which means a success response so this has been deleted to confirm it has a if it has been deleted i will execute that and because we never saw the other one again uh it comes back with zero rows back and if i now still want to delete this deleted contact it should say we are not unable to find that resource in our database so we can't delete it so we have tested these the final one to test is our update and we will use the other id and let's update this list as well because there should be only one and if i pass the id over here and if i pass an updated request so i'll copy that to make things faster i'll actually update all of this to my details from from john doe so using this id i will update this id to be my contact now click on execute success response pack and let's quickly confirm that by going to the database this id was john doe but if i execute it now it becomes me so all our operations the crud operations which is create read update and delete are now working for our contacts api i hope you enjoyed this tutorial and had great fun implementing this alongside me if you did comment a heart emoji letting me know what's the best thing you liked in this tutorial also hit that like button and don't forget to subscribe so that you can get updates to my next upload thank you for watching see you in the next one you
Info
Channel: Sameer Saini
Views: 205,770
Rating: undefined out of 5
Keywords: .net 6 api, .net 6 web api, C# api, api c#, asp net core web api, asp.net 6 api, asp.net 6 web api, asp.net api, asp.net api crud, asp.net api tutorial, asp.net core api, asp.net core api crud, asp.net core api entity framework, asp.net core web api, aspnet core web api, dotnet core web api, dotnet core web api tutorial, entity framework, entity framework c#, rest api asp.net core, rest api c#
Id: 3NWT9k-6xGg
Channel Id: undefined
Length: 50min 35sec (3035 seconds)
Published: Mon May 02 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.