Asp.Net Core Web API - CRUD operations in REST API Tutorial using Entity Framework Core

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello and welcome to my channel in today's tutorial you will learn how to build a restful api and crud operations inside a restful api uh using.net core 3.1 and we will use a mock implementation and we will also use entity framework core to talk to our sql server database to add edit delete and retrieve the employees so if if we and we will use postman to fetch all the results so if we get the employees we have three employees if i want to get a single employee we can do that as well by putting it in the route we can add new employees and we can delete employees and we can edit employees so we'll see how to create all of that in a restful api and dot net core and an ef core so let's jump into the tutorial so we have opened visual studio 2019 and let's start by creating a solution for ourselves so i'll create a new project and from here i will select uh asp.net core web application um and i'll click next i'll give it a name and a location i'm saving it to my desktop and i'll name the application a rest api crud demo you can name it whatever you like and we'll wait for the solution to build and from here i'll i have asp.net version 3.1 and from here i'll select this api option and i'll create so we'll wait for our application to be created now that our application has been created uh let's see by by just running it straight away as to what it offers uh us out of the box so i'll i'll build it first by building the solution where i can also press ctrl shift b and once the build has been done i'll just press start so the build is successful and i'll run it it will open as a chrome window and it should give us it has one web api controller and which is like a weather forecast controller and gives us uh values of of temperatures in celsius and fahrenheit and it's a list of of temperatures like this so we are not going to use one uh we are going to create another one for ourselves uh like an employee employees controller so let's do that so let's create ourselves on by coming here right click on controllers add add a new controller and i'll select the api control option from here and click add i'll name this employees controller and we have this employees controller created for us so in here i basically need five uh api methods um which are get all employees get a single employee uh add an employee edit an employee and deleting an employee so i need all those five methods over here in this controller so uh before doing that let's create a service for ourselves which will basically be used to to fetch data we'll initially start by creating a mock version of it but then later on uh hook it up with entity framework core so that it fetches stuff from the database and it also adds employees to the database so let's do that let's start by creating a folder and call it employee data sorry in here i'll create an interface called i employed data and this will basically have those five functions that i was talking about so i'll start by saying get employees get employees will not take anything as as the method parameter but it will return a list of employee and let's create our employee model now it's time to do that so i'll create another folder called models and in here i will create my employee model initially this will only have two properties one for the id which i am taking as a good and the other one as the name which will be a string and that's it for now and i'll reference this employee model in in our class over here and gets it from models and similar to that i will create a method for method structure for getting a single employee so this will return me an employee it will say get employee single and the key would be the id so it will fetch me the employee by id the next good thing would be to add an employee so add employee method and this will basically or return me the created employee and it will take the employee model as well the next one would be the delete one so i'll not return anything delete employee takes in the employee model and we'll see we have to change the methods uh structure a bit when we are actually doing it but let's keep it as as this for now and the last one would be to edit an employee so i'm returning the employee back and edit employee okay and let's create a mock implementation of this employee data so i'll create a class called mock employee data and after we have successfully uh integrated it this application with mock employee data we will create another one with which uh calls sql employee data and it it basically uses entity framework core to save its data to a sql server so we will do that in the second part of this um solution so in here i basically inherit or implement i employ data and i will implement the interface okay we have a structure ready so if i just close this and come back to employees controller in here we basically first want to inject this uh the smock employee data or i employee data into a controller so let's do that by going to the start startup and in our services section we will add this to our services as a singleton of type i employee data so when when i ask for i employ data i get mock employee data and i've used singleton for a reason because we are mocking the employee data and i'll be creating a couple of employees which i want to remain the same for the lifetime of the application so uh i've used singleton for now and in the constructor of the controller i will now basically inject the i employee data that i am adding to the services and i'll create a private field so now i can use this private field in my controller and this is basically dependency injection it gives me an error because the i employee data is not public so let's make that a public this should be gone now so the first method uh we want to create is get all employees um so i'll start by saying public i action result um get employees and this will be an http get method and the route for that would be api slash employees so it gives us all the employees and i'll return the the employees that i'm getting from the mock employees so i'll say employee data dot get employees and this returns us i have to wrap it in an okay object because i'm passing data back so i'm getting the employees from this mock repository and i'm i'm giving it back as an http okay result so we still have don't have the implementation for the get employees over here so let's do that i will create a couple of employees i will hard code it for for our mock employee data implementation so i'll say a private field of a list of employees and we'll call it employees is equal to new list of employees i'll give it an id of a new code and similarly i will create another employee that's it and now we can use this list of employees to return over here so return employees this will be happy and i guess now we have hooked everything together from the start to end so if we run our application we should be able to see these two list of employees from here in in in our get method so let's spin up our application to see it in action and we will use postman for this to create a new get request and all we need is the the uri for this um and we will define our route as api slash employees as we have defined it uh in our controller so when this is running if i send the request now it should give me the list of employees as we defined it in our mock employee data so now that is running let's create the get single employee method i'll copy paste this and change it to get employee we also need the id to the employee that we want to fetch so i'll paste the id into the uri and the parameter to be a good as id and i'll now call the get employee method and pass the id method to it also i want to check if if the employee is being returned so if employee is not equal to null i'll return the ok response of employee otherwise i will return a 404 not found and we will pass a message to the client saying uh the the employee with id of i'll use string interpolation for this and with the id was not found so we can give a generic message back to the to the client that are calling us and let's create the implementation to this so all i need to return is from the list of employees um get me the single or default so that if it is not found i can pass it as null and i want to match the id to the id so if it is found give the employee back otherwise give a 404 error so let's start this and create another request for for fetching the employee so before giving the same code again we have to send the request to fetch the new covered because it's a mock uh repository and it'll create the quiz again so we want to fetch basically the new guide that was generated and pass it along in the route so if i send this now it should fetch us the first employee if i use the other good it should fetch us the second employee sweet so now we have two methods working let's move on and create the third controller method which is adding an employee so that will be of type http post and we don't need the id in the route we need the employee model as part of our request and we will say employee data dot add employee and pass in the the parameter that we are getting from the client we don't really need this and we will say we will return basically a 201 created that the the server has basically created uh your request and to do that we will return created http back and it needs a uri to the newly created object and the object values as well so we will use http context to to fetch the to or to create the url so i'll use the request scheme i will use the the request dot host and i would use the path and i also want to give the id of the newly generated object so i will use employee dot id and at last i want to give this object value back so i'll pass the whole employee model back and by doing this we should be good if we have created the implementation for it so to implement this mock repository we will basically add employees employee to the list of employees and and before doing this because we don't have an id the client will not pass in id and we shouldn't receive it anyway so we will give it the id to the newly created employee over here and this should work so if i spin up the application now and create a new request in postman which should be of type post and we will use the same route because that's what we have to find in our controller we do need the body so i'm sending a json body and all we need is the name because the id is generated by application i'm passing it my name so if we send this something has gone wrong uh oh because our application never started um it's complaining that i'm not returning anything so let's return the employee even though we are not using it so we can use it as a void but we can change that later on so now that our application has started uh we'll go back here and send the request again and now we can see the newly created object being passed back it's a 201 created from the server and the headers the content type sorry location of the newly created response is this and we can use this location to fetch our newly created employee and it should just work um straight away and if i send this uh here you go it's the newly created employee and it gives us back even the get all employees now gives us three responses employee one employee two and samir senny so our three methods uh in our crud operation of rescue apis are working uh let's go on and implement the next method that is the delete and the edit the next method that we'll create is the delete employee so we'll copy this http post change to http delete we'll use the same route but we'll pass the id um so that the we can identify which one which employee to delete will pass it as a meta parameter and we'll say delete employee and here we'll first see if the if the employee is present or not otherwise we'll return a 404. so we'll get the employee by um by the quid the id and we'll use the employee data dot get employee pass the id in if we get an employee back that means employee is not null uh we will execute the employee data dot delete action um it just will pass the employee over here and if that happens uh delete the employee otherwise return not found because we just say it back to the user that we were not able to find find the employee and the message remains the same so i'll just copy this and to implement delete employee in our mock repository uh we basically have to from the list of employees remove employee and this should work let's see it in action if it's working or not bill succeeded and we will create a new request in postman this will be of type delete and we use this uri which has the id in it uh but we need to change the id so let's get the latest id from all the employees and i'll use this i'll use the second employee and i paste it in my uri and execute send it comes back with employee with id this wasn't found so i'll see what the error is i'll just send this again to see actually it it did work out but it removed it so let's see what what what's happening over here maybe we are not returning a status back that's why and it's always defaulting to not found so in here if the employee deletion is successful return uh you can send an okay back or a 204 as well uh in my case i'll just send an okay empty object back so that if it's 200 the employee has been deleted successfully i'll restart my application we should still have two employees over here because the application restarted and if i send the request to get all the employees i get two employees back i'll use one of the id i'll use the second one paste it in the route send the request it came up with a 200 okay and an empty object back if we do this again it should come up with a 404 because we've already created the employee it shouldn't come here the list of employees is now has only one employee and if we try to fetch it again um we should get a 404 from this get single employee method as well it's a 404 so we can we can say it's working fine so i'll stop this and let's move on to implement the edit or update a method i'll copy the structure it'll be of type http patch and we we need the id over here i'll i'll rename this to edit employee we need the id and we also need from the body we need the employee object with the changes so this is the employee that we changed and let's remove this so the first thing would be basically to see if the employee exists or not so i'll fetch the employee as i was doing it over here i'll copy paste it and see if employee is not null then i basically want to edit the employee and before sending the edit i will basically uh or we can say this is the existing employee existing employee and we'll say if existing employee is not null that means we have an employee in our database we will change the id of the newly created employee so that it can reference from id to be the existing employee dot id and now we will say edit employee and uh we'll return something back over here but let's let's do the implementation part first so we get this employee uh which is the changed employee so it ha it may or may not have all the values in it um so we will fetch the employee again over here so we will call get employee like this so we'll say where existing employee is equal to the get employee and pass the id and we'll just override the values over here we'll say existing employee dot name is equal to employee dot name and this should basically change the existing employees attributes and uh it basically updates the existing value and we can return the employee over here like this so let's see if this is working or not back in here we basically want to return something back um we got the the changed employee so we can return an okay response back with the new employee so which means our employee is working fine if i start this and see if it is working or not i'll create a new http patch method we'll use the same uri as of a delete one or a fetch single one and we will create a body which has the changed employee details i'll the only thing to change here is the name so i'll change the first employee name to my name and let's execute the get all employees to get the latest grid so i'll change the first employee employee one to semi-seni uh i go to my patch function and paste the id into the uri i'll hit send and it gives me a result back and with a 200 message back so to prove it that it updated will come here in the get all employees how it showed employee one this should now change to semiciny so now the two employees with one updated one it's fetching us all of things nicely so we can say that our mock implementation is now done and we have implemented all these five crud operations with retrieval as well and now in in the second part of of this tutorial we will now implement uh entity framework core and save and retrieve delete and edit all our stuff in sql server um so let's let's get started with it to start with entity framework we basically have to install a few new git packages to to in to involve uh entity framework core into our project so we'll go to dependencies and manage new kit packages the package we will search for is microsoft dot entity framework core dot sql server i'm installing this because it also installs all the dependencies that we need for the entity framework core to be installed in our project so i'll install that along with that i will also install entity framework code.tools this is basically used to for our core migrations all right so our new kit packages have been installed and as you can see in our database i'm going to use the server and we don't have any databases at the moment so we will create a database using entity framework core migrations and let's start by by adding or getting adding the context to our solution so i'll right click on the project add new folder and say employee context are now we don't even need this folder let's let's include this as part of our models i'll create a class over here and call it employee context this basically inherits from db context and we will use microsoft entity framework core i'll create a constructor of this class and basically use the db context options of type employee context and pass this to the to the base constructor in here i will also create a dbset property of the employee model so and call this employees this will basically act as a table which is a db set of employees so employees would be a table created in our employee db database and in in our employee model let's put this as a key and name as a required field we can also put max length property on it max length takes a few parameters here like the length let's say 50 as the length and an error message if it exceeds 50. okay and after that we have to add the the employee db context as part of our startup to basically inject the service so we will do two things over here one is to add the tv context so services start add db context pool and you can read about the differences between db context versus tb context pool of of type employee employee context and it takes options in here so i'll say option start sorry use sql server and you sql server requires a string connection so uh connection string so we will define a connection string in our app settings module by by defining a section of connection strings and mentioning the employee employee context connection string this would be this would basically take a format of a server server i would call i would use this server name i would paste that here it would also need a database which we don't have at the moment so i'll mention employee db and a trusted underscore connection is equal to true it takes that so we can fetch this connection string in our startup by using the configuration over here so we will say configuration dot get connection string and we will mention the key over here which we gave so employee context connection string so this should basically fetch us the connection string for our sql server along with that because the app db context pool uses a scoped um lifetime uh we would use instead of a singleton which we are using for the mock employee data we would now use add scoped and we will change the smok employee data to to be called as another implementation which we will define now so in our employee data we would create another implementation called sql employee data because we are talking to a sql server now i'll add the implementation this would also inherit from [Music] i employ data and i will implement the interface okay and just to get references here okay so our startup would now say if i'm asking for employee data and give me the sql employee data and this should work now it's showing me some error because i guess it needs another bracket so i'll close the startup file and in our because our employee controller is already hooked up with everything it doesn't need to change uh we just want to implement get all employees over here so now we can in here in the constructor get the employee context we can say we can call it as employee context and store it in a private variable so now that we have the employee context over here let's fetch the employees from the context so employee context dot employees and dot do list so this would basically return all the employees from from the table of employees to implement gate employees we would basically return uh employee context dot employees dot single or default like we were doing in our mock implementation if the id matches return the employee we can do this or we can we can use find as well find usually works by if you if you are doing this ah dot employees dot find by id and something is wrong over here or basically it doesn't even need that it needs the id field over here it fetches an employee to us and it can be null so we will just return the employee because we are handling the status outside of this method um and let's see till here if if our entity framework connection is all working or not but before that because we don't have a database and and a table let's run our migrations now we will go to tools and we will go to nuget packages manager console and we will type add migration and hit enter it's asking us for a name for the migration so i'll call it initial i'll call it initial migration and hit enter this will create a migrations folder for us it's basically code uh which represents a table to be created in the database so it has created a migrations folder with an initial migration class and to basically uh create the actual table we will call update database so till now before hitting this i can refresh this database to show you that nothing has been created yet but after i execute this it runs the previously created migration just the latest one so it will update the database for us because this script contains all the things necessary to create the table and the database so once the script has run successfully you you will be able to see um the database uh in in our databases so the employee tv and you would see one table in it which is the employees table and also you can see the ef migrations history table is here if i select it it shouldn't be anything over there there's no data but has two columns the id and the name which we defined in our employee model and the employee context had this employees dbset thing which creates the the table in our database so now basically if we start our application and we have our employees controller uh everything should work as usual but it shouldn't fetch anything so let's see if we get an empty array back so start the application well actually we'll face one error because we haven't uh said that we should use a sql employee database or i have forgotten that you've said it oh we have already done that so let's run our project and once this is up and running we'll go to the get all employees and we'll hit send this should basically fetch us an empty list of employees you can see uh it's an empty array so it's it's working as it should so let's uh implement the the add functionality so that we can add an employee and we can see if we are able to fetch it or not so i'll go to my sql employee data implementation and in the add employee i'll basically use the context so i'll call employee context dot add dot employees dot add and i'll pass the employee object that we are sending before doing that we also want to create the id because it's not an incremented id so we will create a good and add the employee over here and after doing that we will save the changes and this should run and return the employee that we created and if we run this now and we go to our add method in the add employees it's a post type let's create an employee with the name samiaseni so when i run send i should get back a 201. it's still trying to build and run sweet so we got 201 back and the body contains the the newly created employee with the id as well and the 201 the headers in the location we can fetch the employee by just copy pasting it in our get call so if we get the single employee we should basically get 200 and the employee details over here so this is all working and the gate all employees should now have one result which it has let's go and check the database so if i select star on the employees table again i should now see one employee over there so this is working uh nicely now let's implement the other two actions as well which is the delete and the edit in the delete one we will basically find the employee so we will say where existing employee is equal to employee context dot employees dot find find the employee and if employee if there's an existing employee then we want to delete it employee dot uh remove remove takes the entity so we'll pass the employee object over here actually the existing employee over here and uh basically let me check the reference to this again if we are finding it already we don't need to do that again so we are getting the employee already so we don't need to find it again so in here in the delete implementation i'll skip this and directly call the remove uh employee because we are fetching it already through our database so we don't need to return anything as it's avoid so this should work and we need to save changes of course and for the edit employee we will fetch the employee here because this is the edited employee so let's fetch the employee like this and see if the existing employee is not null then we need to basically update it so we'll pass the updated entity we'll use the employee dot id over here and in our context dot update it takes the entity again so we'll pass in the employee over here basically has everything in there because in the controller we we are basically editing the id before sending it to the employee so we just have to update it like this and save changes so return takes the changed employee which we can send it back so now that we have our implementations for all the things ready uh let's see this in action i'll spin up my solution again and once it is up and running i'll call get all employees i'll hit the same button it should just give me one at the moment but we will add one more so that we can test the delete and the edit operations so it's now up and running and it's hitting the get request we will add a few more so we will say employee 1 and hit the same button comes up with the 201 created i'll add employee 2 and similarly employee three so in our table we should have four records now instead of just one um now let's try to edit uh an employee now to edit an employee i want to make a small collection in the sql employee data class file um instead of passing the employee over here so this was employee rather than that because we want to track the entity we would now make the name equal to the new name that we want to edit and we want to send this to entity framework to update and then save changes so with having this we will now be able to track the entity and update the changes to the sql server so let's try that we will use employee employee tools id and we'll paste the id over here and we'll rename employee to to we call as employee five and if we send this now we should get a 200 response back and as soon as we get the response back we should also see that the new employee data has been changed to employer 5 as you can see it now and if we go to our database if we refresh this again employer 2 has now been changed to employer 5 so edit works as expected and now if you want to delete this employee 5 i will just copy paste the id from here to the route and if we send this delete button it says as 200 okay without in any body that means our employee should have been deleted from the database and if we just try to do that again we should get not found error and the get all employees should fetch only three results now so as you can see we have successfully created a crud um restful api so we were able to retrieve values we were able to delete values add new employees edit it and all this using entity framework core um i hope you all liked the video if you liked it uh just give it a thumbs up um do subscribe to my channel for some more awesome content and and keep watching cheers have a good [Music] day [Music] you
Info
Channel: Sameer Saini
Views: 81,757
Rating: undefined out of 5
Keywords: ASP.NET core web api, rest api .net core, rest api Asp.Net Core, rest api demo, rest api crud operations, crud operations in asp.net core, Entity framework core crud, entity framework, asp.net core web application with entity framework core, EF core crud, Rest api C#, Rest api tutorial
Id: r4LlIhyQ9GY
Channel Id: undefined
Length: 52min 25sec (3145 seconds)
Published: Sat Oct 17 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.