Asp.Net Core Web API CRUD Operations Using EF Core and SQL Server

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello all this is Anis with you welcome to my channel in this tutorial we are going to create two projects one rest API credit server and MVC API correct client first let's see the demo of the projects which we are going to create in this tutorial the right side project is API crud server and the left side project is MVC API correct client let's see the create action first click create new button then enter the first name last name phone number and email address then when we click the create button this form will be submitted to a API server you can see the API server project status window in the right side bottom corner yes the form is submitted now and the customer record is saved successfully we are redirected to the index page it looks like everything happened in one application but it is not there are two applications and the communication between the client and server happens through the rest API technology and next we will see the edit action method actually the edit action method uses the HTTP put request to communicate with the API server whereas the create action method use the HTTP post request to complete the action let's modify the phone number and press the save button to update the changes to the database through the API server perfect the changes are updated successfully to the database so the edit action is working fine next we will see the details section details action method uses the HTTP get request to retrieve the customer details from the API credit server see the record is successfully retrieved and displayed next we will see the delete action the delete action uses the HTTP delete request to remove the results permanently from the API server press the delete button in the delete confirmation page perfect the record is deleted now so all the credit methods are working fine let's see how the projects are made from this scratch start Visual Studio 2022 and then select create a new project from the site menu after that from here select asp.net core web API project template from the site menu then after press next button in here give the name of the project as API credit server and save this project in the C drive after that press the next button in here select the target framework as dotnet 7.0 and leave the authentication type to none and then set the checkbox label desk configure for https as checked after that set the checkbox labeled as use controllers also to checked then set the check box labeled as enable open API support to checked this is because we are not using any JWT security tokens as of now later we will add the support for JW tokens then click the create button and wait for the scaffolding task to complete creating the project in case if the published dialog box prompts click the cancel button we are not going to publish this project now open the solution Explorer from The View menu and then expand the controllers folder and open the weather forecast controller file notice this file this has a annotation called as API controller In The Head of the Class name this makes the class as an API controller and this class has only one method named get and this get method is an API method and this method also has a HTTP get annotation and API name is set as get weather forecast so that this method can be accessed by calling by the name get weather forecast okay now let's convert this application to an API credit server right click the projects folder and click add and click new item and select class as the item type and give the name as customer this class is going to be the model for the customer table then press the add button now the customer class is created in API Solutions you don't keep the class files inside the models folder but if you wish you can create a folder named as models and keep all our model 4 classes inside it I'm just keeping my customer class in the root folder just to make the project as simple next we need to add properties to the customer class file off the screen I have added five properties to the customer class file namely ID first name last name phone number and email ID hope these properties are enough to create our API credit solution next we need to install the Entity framework core so go to tools and select nuget package manager and then select manage nuget packages for Solutions and here click the browse button and then enter EF core SQL server in the search box after that select the Microsoft dot Entity framework code.sql server and here check the API credit server project and select the latest version of EF core from the version select drop down box as of this recording the latest version is 7.0.3 and click the install button in case if you are prompted with the preview changes dialog box then click ok to proceed further then after click the I accept button in the license acceptance dialog box and wait for the installation to complete after that we need to create the DB context file we will keep our DB context file inside the data folder so let's create a folder named as data right click the data folder and select new item and select the class as the item type and give the name of the class as API DB context and press the add button after that inherit the class from the DB context based class this DB context class is in the Entity framework code namespace so include this namespace in the using section and then add the Constructor method which will pass the options parameter to the base class after that add the DB set property for the customer class and name the property as customers then open the app setting.json file and add the connection string here please notice I have given the database name as API crud example after that open the program.cs file and in here first add the API creditserver.data namespace and Microsoft dot Entity framework core namespace in the using section then add builder.services.addb context of API DB contacts with options equals to options dot use SQL Server of Builder dot configuration.get section of connection strings colon DB dot value and then go to the nuget package manager and select manage nuget packages for Solutions and here click browse and enter EF code tools in the search box then from the search results select the Microsoft dot Entity Framework code.tools then from the right side project selection grid select API credit server and then select the latest version as of this recording the latest version is 7.0.3 after that press the install button if you are prompted with the preview changes dialog box then press ok after that click I accept in the license acceptance dialog box and wait for the package installation to complete then open the package manager console window and in here type add Dash migration and leave a space and type create DB within codes and press the enter key then type update Dash database and press the enter key oh errors a connection was successfully established with the server but then an error occurred during the login process blah blah blah blah blah if you get this error then don't worry till.net6 EF core was not using the secured certificates but from dot Net 7 onwards if core is using the secured certificates so to fix this error open the app settings.json file and add trust server certificate to true in the connection string and then save the file and close it after that go back to the console window and enter update Dash database and press enter again wow this time the command executed successfully and the database is also created then next we need to create the customer API controller right click the controllers folder and then click add and select controller after that select API from the side menu then select empty API controller and press the add button give the file name as customercontroller.cs and then press the add button then after add the API credit server.data namespace to the using section or in the global using section of the program.cs file both the ways are correct then add the private read-only variable of type API DB context and name it as underscore context then create the Constructor method for our customer API controller and inside it set underscore context variable to the parameter named context after that let's create our first API method it can be named simply as get or get customer both are correct here it is showing error below the to list async method to fix this error add the namespace Microsoft dot Entity framework core to the using section notice after adding the namespace the error got disappeared actually this method will provide the list of all customers to the color method we will add the pagination parameters later to this method then let's create our next method this method also will be named as get customer but in this method we are adding a parameter named ID of type integer so this method will fetch the requested customer details based on the past ID parameter if the customer is not found then this method will return the not found object not font is one of the action result type notice here we did not use any async keyword so this method will execute in the synchronous way actually there is not much performance differences between synchronous and asynchronous methods in the API Solutions synchronous method will block the calling thread till the action completes whereas the asynchronous methods will not block the calling thread both are right use whichever you like okay let's go to the next method next method is create this method will create the customer in the database normally in the MVC credit applications the create action methods send the control to the index page where all the customers will be listed but in the API Services the method will return the customer object back to the caller method I prefer this approach because in our case the customer object comes without the ID after creating the customer object in the database the customer ID is auto generated in the database table now we need to return this customer ID to the color method so it is best to return the customer object back to the color method since now customer ID field is filled in the customer object next let's do the update method actually in MVC application we use edit action method to update the record and there will be two edit action methods in the MVC application one with the HTTP GitHub and the other one with the HTTP post verb but here we use the get customer method to retrieve the customer record and update method to update the customer since we already have the get customer method we will only write the update method now notice here I have used the HTTP put web for the update method it is always recommended to use the put web whenever you are doing an update action to the backend table but we can also do the same action using the post verb next let's do the delete method for the delete method we are using the web HTTP delete in the delete action we first find the customer by the ID if the customer is not found for the past ID then we return the not font result not found is a negative or failure response if we want we can also pass a message inside the not phone response like incorrect customer ID or customer not found or whatever okay our API server is ready let's build and run the API service this is the Swagger window earlier we were using Postman to test our apis but from.net6 onwards Microsoft has added the Swagger support to the asp.core API project in case if you are wondering what is Swagger Swagger is an open source set of rules specifications and tools for developing and describing restful apis the Swagger framework allows developers to create interactive machine and human readable API documentation and now click on the get button to expand the API drop down window and then click the try it out button this will make the execute button and the parameters needed to call this API visible let's click the execute button to test the get customer API method since there is no records in our database it is returning empty Json but the response code is 200 that means there is no error in the API call the number 200 is the success code we will see more about the codes when we develop our API correct client application now let's close the get customer apis drop down window then let's check the post method I mean the create action method so expand the post method drop down window then click the try to button after clicking the try dot button the execute button and the response body Json window will be displayed in the response body text area let's fill the first name last name phone number and email ID properties of the Json let's give the first name as Anis that's my name last name is Muhammad and phone number some dummy number and email ID as any set anis.com after filling the Json text area press the execute button perfect the Json data is posted and we got the response from our API server let's see the response the response code is 200 that means the method called got succeeded now notice the response Json carefully when we post we posted with IDs 0 but in the response Json the ID is showing us one for the customer and is Muhammad to understand this better let's have a quick look on our create API methods code see here we are receiving the customer data without ID and then we are adding it to the database using the context dot save changes async method after that AF core will retrieve the ID for the created customer and will set the retreat value to the customer object then the method will send back the customer object to the color method this is why we are able to see the IDS 1 for the newly created customer in the response Json okay let's close this create method and move on to the next method the next method is get let's click this method to open the parameter window of this method then click the try it out button to enable the parameter window after that enter the ids1 and press the execute button to retrieve the customer with IDs 1. perfect the customer with ids1 is retrieved from the database by the get customer API method so this method is also working fine let's close the get method window then after open the put method drop down window and click the try to button to enable the parameters on Json window this method requires two parameters first one is customer ID and the second parameters customer Json so first enter the IDS 1 and then enter the Json properties in the Json window enter ids1 Then I am changing the first name to Muhammad and the last name to Anis earlier first name was Andis and last name was Mohammed now I just change the first name to last name and the last name to first name then change the phone number and email ID also now let's press the execute button perfect the update customer call is succeeded see we got the Response Code as 200 that means the call is success let's close the put method first and then open the first get method this method will list all the customers of the database but currently we have only one customer Let's cross check the changes done by our update method I mean HTTP put web method click the try dot button after that click the execute button perfect the method is executed successfully let's scroll and see the result notice the response Json the changes we made through the HTTP put method is updated successfully to the database I mean the first name is now changed to Muhammad and the last name is change to Anis okay now all the methods of our API server is working fine so let's create the API client correct project that's going to be very interesting so please don't go away please watch the full video start Visual Studio 2022 and click create a new project then from the right hand project type selection grid select asp.net core web app with model view and controller and in here give the project name as API correct client then set the project location as you wish or to C drive after that set Place solution and project in the same directory checkbox to checked then click the next button in here set framework version 2.net 7.0 and leave the authentication type to none then leave the check box configured for https to checked after that click the create button and wait for the scaffolding task to complete now click the view menu and open the solution Explorer window then right click the models folder and click the add menu and then click the new item and in here give the file name as customer.cs and press the add button after that download the API credit server project from the displayed URL then extract and open the downloaded API credit server project after that run the project in case if you have not created the database for the API credit server project then run the add migration followed by update database command in the package manager console window after that open a browser then go back to the API server project Swagger window and expand the get method drop down window then click the try to button now click the execute button then from here copy the API URL of the get method to the clipboard then go back to the browser and paste this URL in the address bar and press enter well now we got the response Json from the API server copy the response Json by pressing Ctrl a followed by control plus c then go to the API credit client project and here open the customer.cs file after that click edit and select paste special and then click the paste Json as classes as shown after that delete the root object and empty customer class from the customer.cs file then rename the class 1 to customer after that add the validation attributes to the property heads so that the client-side jQuery validation will show the error spawn elements in the browser when requirements are not met ok now the customer class is ready this is how you convert your Json classes to c-sharp classes next we will create the customer controller which will do the correct operations in the client Side by connecting to the API server right click the controllers folder and then click add and select controller then here select MVC controller empty after that change the file name to customercontroller.cs and press the add button okay now the customer controller is created in here delete the default index action which came with the scaffolding task and then let's add our index action notice this action method looks like a normal index action of a current application but this method is incomplete we need to insert a important line in the middle which will fetch the customers list from the API server don't worry we will do that in few minutes please wait and next we will add the create action method this is also incomplete and it is very similar to our normal credit applications create method then next is the details method there is nothing new in this method to explain so please just have a quick look on it and copy it after that let me paste the edit method this is also very similar to the create action method currently it is incomplete but no worries we will complete all the methods very soon just you need to wait for a while now only the delete method is pending let me paste that also okay now we have completed all the action methods and we are ready to inject the codes to access the API server so let's do that hello all making YouTube video takes lot of time and efforts but all these efforts should have a meaning so please like comment and share this video thanks a lot let's continue to the tutorial please do not forget to subscribe to this Channel and press the Bell icon to get notified after that build your project if no errors then start creating The View files open the customer controller and scroll to locate the index method then right click on the index method then click add view in here select razor View and click add after that select the action template as list then select the model class as customer then press the add button and wait for the scaffolding task to complete okay now the index view file is created successfully then scroll down to locate action links button in here notice the route IDs are commented so please uncomment and set the route IDs then next we will create the view file for the create action method in the same way after that open the create.cs HTML file and comment html's code of labels and text box for the ID property because ID will be created by the API server in the same way let me create The View files for details edit and delete actions but this time I am doing it in 64 x speed in the interest of time in the edit view file we need to do an important change in the code that is to add the read-only attribute for the ID text box otherwise user may change the value for ID property and then the API service update method will not work and next let's create the view file for delete action method also in the 64x speed okay now we are done with The View files let's create the API Gateway class and then we need to add this class to the services collection so that it will be served by the dependency injection when needed so open the program.cs file and add builder.services.adscoped of API Gateway as shown in the video this is a very important step if you don't add this line then sorry your program will not work okay now go back to the API gateway.cs file and there add a private variable named URL and set the URL to your endpoint address of your API server in real time we need to add this to the app settings.json file but to keep it simple I directly hard coded here then next add object variable of type HTTP client we are going to use this HTTP client to connect and make calls to our API server after that let me paste our first API client method named as list customers this method will retrieve all the customers from the API server please see the code implementation carefully and copy it correctly this code looks complicative but it is very easy to understand first we are declaring a list variable of type customer then we check the API endpoint URL if it is user secured protocol I mean https then we need to set service Point dot encryption to tls32 when we do this all Communications happening through this socket will be encrypted next we are calling the API using the get async method of the HTTP client object after that we are checking the status code of the response if it is 200 then the call is success if the status is Success then we will download the results to a string variable here we know if the call is Success then the output string will contain the collection of customers so we deserialize the string by passing the object type as customer and collection type as list then we check if customer exists in the D series object if it exists then we set it to our customers list and return the customers list to the color method okay list method is done let's go to the customer controller and add this to the index action method in the customer controller first declare object variable of type API Gateway this is the object which is going to do the all cred operations for our customer controller actually in the normal mvac credit applications we declare the DB context which will do the credit operations but here DB context resides on the API server which we cannot see also and next add the Constructor method with an input parameter of type API Gateway the value for this parameter will be served by the dependency injection then in the index method add the line to set the customers equal to apagateway dot list customers after that open the layouts.cshtml and add the menu link to access the customers module in here copy the menu link of home and paste it below then change the controller name to customer and change the menu text to customers okay all set now let's build and run our application let's click the customers menu notice the customers list is fetched by the API client from the API server in the right hand side you can see the API server status window there it shows the command executed to fetch the customers list from the database OK next let's write the create customer in the API gateway.cs file so let's stop the API correct client application and open the API gateway.cs file let me paste create customer method to the API gateway.cs file this method is slightly different from the list customers method because in this method we are using the HTTP post web so please listen carefully the first two lines are same we already seen this in the list customers method then in the next line first we are serializing the customer object to the Json string using the Json convert dot serialize object after that we are calling the HTTP client's post async method notice the parameters of the post async method carefully the first parameter is the API URL then the second parameter is very important one we are passing the Json string inside the string content the beauty of the string content is we can say what is in this string I mean the string as Json so we say application slash Json and the encoding type is encoding dot UTF 8. after that we are receiving the result of the post async method and storing that in the HTTP response message object and then we are checking the status code of response by calling the response dot is success status code if it is Success then we read the Json result from the response dot client after receiving the result we are DC releasing the result to customer object using the Json convert dot DC release object and then we are returning the customer object to the calling method actually most of the codes are same only the processing method is little different from the list customers method otherwise it is almost similar to the list customers method okay now let's go to the customer controller to complete the create action method open the customercontroller.cs file and locate the HTTP post create action method and add API Gateway dot create customer of customer then run the application after that click the customers menu and then click the create new link in here let's enter first name as Anil and last name is a nice person who taught me programming 25 years back after that enter some fake number and some fake email ID okay we are ready let's click the create button wow the customer data is saved successfully and customers list is displayed notice the commands executed in the API server status window which is on the right side of the screen so the create action method is also working fine in the API client and in the API server please note the create customer method is using the HTTP post verb so we have seen HTTP get and HTTP post API web so far only HTTP put and HTTP delete is pending next we will do the details action method to do that fast we need to add the get customer method to the apagateway.cs file this method is very similar to the list customers method only difference is this is passing the parameter ID to the API server otherwise it is almost same to list customers method and then we will go to the customer controller to complete the details action method in here add the line customer equals to API Gateway dot get customer by passing the ID then build and run the application and click the customer menu after that click the details link of the first customer perfect the details action method is also working fine so now we know how to pass the parameter to the API server using the HTTP gut verb and next we will do the edit action method let's stop the API correct client project to go to the design view of the visual studio 2022 after that open the API gateway.cs file and in here let me copy and paste the update customer method this update customer method is almost similar to the create customer method but in the create customer method we had used the HTTP post web but here we are using the HTTP put web and we are also passing the parameter to the URL then the next major difference is in this method we are not reading the result data it only checks is the success status code is received if the success code is received then the control returns to the controller's edit action method otherwise it throws the error okay let's complete the edit action method of the customer controller open the customercontroller.cs file and locate the HTTP get edit action method and here set customer variable to API Gateway dot get customer of ID then remove the new keyword from the customer variable declaration line as that is of new use after that scroll to locate the HTTP post edit action method and here call the API gateway.update customer method by passing the customer object variable to it please note both the edit action methods carefully and copy it okay we are done with edit action methods so let's run the application to verify it in here click the customers menu and then click the edit link of our first customer named Anis Muhammad and then change the phone number then change the email address also after that press the save button notice that the phone number and the email address got changed so our edit action method is also working fine that means now we know how to access an API server using the HTTP put web also we are almost done only the HTTP delete web spending let's do the delete customer method so stop the application then open the API gateway.cs file after that let me paste the delete customer method delete customer method is very similar to update customer method everything is safe the only difference is here we use the HTTP delete web and in the update customer method we used the HTTP put web okay then let's open the customer controller to complete the delete action method locate the HTTP get delete action method and there remove the new keyword from the customer variable from the Declaration line then set the customer object variable to API gateway.getcustomer of ID then in the HTTP delete action method called the apagateway.delete customer method by passing the customer dot ID okay all set let's run the application now press the customers menu from here let's click the Anil manual record let's try to delete the Anil minute record by pressing the delete button notice the record of Anil moon is missing because it got deleted so all the credit operations are working fine now we are able to make all calls to an API server from the MVC API client with this I am completing this video before I sign off I request you to subscribe and share this video I would appreciate if you would like and subscribe to this channel so that you will be notified for all of the new videos that I will be posting thank you and bye for now
Info
Channel: CodeS
Views: 16,072
Rating: undefined out of 5
Keywords:
Id: 24JVFVVk9K0
Channel Id: undefined
Length: 48min 31sec (2911 seconds)
Published: Tue Mar 14 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.