Introduction
In this article we are going to create WEB API in ASP.Net core using Entity Framework Core’s Code first approach. In this we are creating a simple crud operation of employees and test it using Swagger. In this API we are not going to use authentication, we added this in my upcoming articles.
In this article
- Create ASP.Net Core Web API Project
- Add Entity Framework and Create Tables
- Create Service to perform CRUD Operation
- Implement Service in Controller
- Test API Using Swagger
Create ASP.Net Core Web API Project
Step 1
Open Visual studio and create new project. Here I am using visual studio 2019 you can use as per your system and requirements.
Step 2
Find and select Asp.Net Core Web API and then click on next button.
Step 3
In next wizard you have to enter following things and then click on next button
- Project Name
- Location of your project (Path where you want to save your project)
Step 4
In this wizard screen you have to specify following things and then click on create button.
- Target Framework, Here I am using current version install in my system which is 5.
- Authentication type: Currently in this project we are not using authentication so here I select none.
- Configure HTTPS: If you host your API with secure https connection then you can check this box. It will add redirection in your project which help to redirect http request to https automatically.
- Enable Docker: For this project we are not using docker so leave un check
- Enable Open AI Support: If you want to implement Swagger in your project then you have to check this box. In this project we are going to use swagger so I check this box.
Now your project is created and you can see project structure in below image. Remove extra files like weather controller and model if you don’t want it.
Add Entity Framework and Create Tables
For using Entity framework in our project and create table using code first approach we have to follow below steps.
Step 1
Right click on project name and click on Manage NuGet Packages.
Step 2
Install the Following NuGet Packages.
- Microsoft.EntityFrameworkCore.SqlServer : This Package is use for interact with SQL Server from Our C# and .Net Core.
- Microsoft.EntityFrameworkCore.Tools : This package is contained various command like Add-Migration, Drop-Database, Get-DbContext, Get-Migration, Remove-Migration, Scaffold-DbContext, Script-Migration, Update-Database. In this article we use Add-Migration and Upadate-Database command.
- Microsoft.Extensions.Configuration : Using this NuGet package we can read data from our app setting file. We will get our connection string from the app setting file.
Step 3
Now we add a new folder in our solution to contain various classes. For adding new folder in our solution right click on project name the click on Add then click on New Folder and gave name as Models.
Step 4
In this Models folder we will use our entity classes. Right click in this folder then Add then Class. Give suitable name for your class.
Step 5
Add fields as you want to create in your table. Here I create Employee class with following fields. Here key attribute define that use this column as primary key.
Step 6
Now we create a context class which use as a middleware to SQL Server. Add new class in your Models folder and add constructor and Employee DbSet as seen in below code.
Step 7
Now we have to connect SQL Server with our project, for that we need connection string and this string we are going to add in app setting file. Add your connection string as showing below.
As see in above code here I pass . (dot) as a server name because I used my local pc SQL Server. Then gave database name Tutorial, if this database not exist then it will generate automatically. Here I not give any username and password because I use windows authentication for this if you want to use other method to login then pass username and password.
Step 8
Now we have to add Db Context in our startup file for this open startup file and add following code.
In ConfigureService Method, we add our EmpContext class and pass connection string in it by getting from our appsetting file using Configure.GetConnectionString() method.
Step 9
Now open Package Manager Console by click on Tool Menu then NuGet Package Manager then Package Manager Console.
Step 10
Add following command.
Add-Migration Init
Here Init is our name of migration, you can give as per your choice. Hit enter.
Step 11
As you can see in your solution new folder named Migration is created and in this project there is two file. One is EmpContextModelSnapshot and other one is *_Init , here * mean date time stamp.
In this init file, there is below code. This code execute when we use our next command and it will generate new database and new table Called Employees.
Step 12
For now, our database and table is not created for make changes in Server side use below command.
Update-Database
Now you can see in our SQL Server Employee table is created with same fields as we add in our model.
Create New Response Model
For save and delete we are going to return new model for send data to user. So create new folder called ViewModels In your solution because we want to store Entity classes and Other classes in different place. Add new class Called ResponseModel in this folder with following properties as seen in below code.
Create Service to perform CRUD Operation
In this project we are going to use repository pattern to interact with database. We are not going to call database in our controller, instead of we create new service and call database there. For this we are going to create one interface and one class and then add dependency injection for these.
Step 1
Create interface with following methods as seen in below code.
Step 2
Create new class and implement interface in this class.
Step 3
Now open your startup file and add below line of code in ConfigurationService Method to add dependency for our class and interface. This means when we call any method from this interface it will automatically call a method from the class.
Constructor in Service
We are going to use DbContext in our service class for this we add dependency in constructor as you can see in below code.
Get All Employees Method
In the above code, you can see that we are return list of employees from this method. For retrieve data from database, we use toList() method of DbContext.
Get Employee Details By Id Method
In the above, you can see that this method take one parameter, ID. We get employee object from database which employee ID match to our parameter id.
Save Employee Method
As you seen in above code, we take employee model as a parameter. Then we called our get details by id method to get details of employee by id and store In temp variable.
Here if employee Id is coming with model which means we have to update employee and if employee id is null or zero then we have added new employee.
If we got data in temp variable then we assign new data from our parameter model and update employee context and with that we also assign message to our response model.
And if we got temp variable as null, then we insert parameter model as in context and pass message in response model.
In last, we called save changes method of context to save all changes like insert update and set Is Success property of response model to true. If any error occur, then we update is success to false and pass error message in message property.
Delete Employee Method
In delete method, we take employee id as parameter. And call service method get detail by id for get employee details.
If employee found then we remove this employee by calling remove method of context, else we return model with Employee not found message
Implement Service in Controller
Now our service is ready, so now we implement it in our controller.
Step 1
Add new controller by Right click in Controllers folder then click in Add then Controller.
Step 2
Now select API from filter and select API Controller – Empty and click in Add button.
Step 3
Now give an appropriate name and click on Add button.
Constructor Of Controller
In the Constructor of our controller, we implement dependency injection for our service.
For this controller, we are using routing with action methods. For example if user called Employee with Get method then it will call Get List Of All Employee Method and if user called Employee/{id} with Get then it will call Get Employee Details By Id Method and If user called Employee with POST method then it will call Save Employee Method and same as if user called Employee with Delete method then it will call Delete Employee Method
Get List Of All Employee Method
in above method we call method from our service and assign to variable. If variable not null then we return ok status with this variable, else we return not found.
Get Employee Details By Id Method
Save Employee Method
Delete Employee Method
Test API Using Swagger
While creating this project we are added open ai support so when to run this project it will open swagger page as seen in below image. From here we can test our API.
Add New Employee
Expand Save Employee Method and click on try it now button. Now json fields are editable, to add data in model as seen in below first image and click on execute. In the second image, you can see that data is updated in our table also.
Update Existing Employee
In this request we are pass same model as we pass in previous request but in model we pass id also.
Get Employee Details By Id
Get List of Employees
Delete Employee
If Employee Not Exist
Conclusion
In this article, we create simple Employee API with Entity Framework Core. In future articles, I implement authentication and also connect this API to Angular. So if you find this article helpful, kindly share with your friends.
0 Comments