Create APIs Using .Net Core 3.1 | REST API in .Net Core 3.1 with Entity Framework

Introduction to this tutorial

 
We will create a .Net Core API project using Visual Studio 2019 and framework version 3.1 We will also create a database and table in the database (to perform the CRUD Operations) using the SQL Server Management Studio 2019. You can use SQL Server version 2008 to the latest version.
 
I hope you will enjoy this tutorial and that it will be helpful for you.
 
Let's see the flow step by step. First, we will create a database and a table inside the created database. Use the below command to create the database materials.
  1. Create Database APICoreDB  
  2. Use APICoreDB  
  3.   
  4. Create table Employee(Id int primary key identity(1,1), Name varchar(50), Department varchar(20), Salary decimal(10,2))  
  5.   
  6. Insert into Employee(Name, Department, Salary)Values('John''DotNet', 50000)  
  7. Select * from Employee  
Create the Web API Project using Visual Studio 2019.
 
Steps
  1. Open Visual Studio
  2. Select Create a new project
  3. Select "ASP.NET Core Web Application (C#)" from the left panel
  4. Select "ASP.NET Core Web Application" from the right-side panel
  5. Now Click on the "Next" button 6. Give the Project name as "WebAPICore"
  6. Select the location or leave it as it is
  7. Now click on the "Create" button
You can watch this complete video here.
 
Now add three folders in the created project with the name "Models", "Services" and "IServices".
 
Now add the required references to work with the SQL Server database and .Net Framework
 
To do this, follow these steps:
 
Go to Tools menu => NuGet Package Manager =>Package Manager Console
 
Run the below commands
 
PM> Install-Package Microsoft.EntityFrameworkCore.SqlServer
PM> Install-Package Microsoft.EntityFrameworkCore.Tools
 
Now configure the database and add model classes. To do this, follow these steps:
 
Go to Tools menu => NuGet Package Manager =>Package Manager Console
 
Run the below commands:
 
PM> Scaffold-DbContext "Server=DESKTOP-TA2C85E\SQLEXPRESS; Database=APICoreDB; User ID=sa;Password=123456;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
 
After running the above command you are able to see two files are added into the Models folder with the name
"APICoreDBContext.cs" and "Employee.cs"
 
Add connection string in the appsettings.json file.
 
"DbConnection": "Server=DESKTOP-TA2C85E\\SQLEXPRESS;Database=APICoreDB;User ID=sa;Password=123456;"
 
After adding the above line, your file will look as below:
  1. {  
  2.     "Logging": {  
  3.         "LogLevel": {  
  4.             "Default""Information",  
  5.             "Microsoft""Warning",  
  6.             "Microsoft.Hosting.Lifetime""Information"  
  7.         }  
  8.     },  
  9.     "AllowedHosts""*",  
  10.     "DbConnection""Server=DESKTOP-TA2C85E\\SQLEXPRESS;Database=APICoreDB;User ID=sa;Password=123456;"  
  11. }  
Add a class in the folder "Services" name it as "EmployeeService.cs".
 
Add Interface in the folder "IServices" and name it as "IEmployeeService.cs".
 
Now it's time to manage dependency injection.
 
To do this open the Startup.cs file.
 
Add the below lines inside the function ConfigureServices.
  1. services.AddHttpClient();  
  2. services.AddDbContext<APICoreDBContext>(options =>  
  3. options.UseSqlServer(Configuration["DbConnection"]));  
  4.   
  5. services.AddTransient<IEmployeeService, EmployeeService>();  
After adding the lines your ConfigureServices function will look as below.
 
 
Now add the interface methods inside the file "IEmployeeService.cs".
  1. IEnumerable<Employee> GetEmployee();  
  2. Employee GetEmployeeById(int id);  
  3. Employee AddEmployee(Employee employee);  
  4. Employee UpdateEmployee(Employee employee);  
  5. Employee DeleteEmployee(int id);  
After adding the above methods your "IEmployeeService.cs" file will look like below,


Now implement the interface method inside the file "EmployeeService.cs"
  1. You need to inherit interface then
  2. Create an instance of the DBContext class using the constructor
So that we can use it to communicate with the database as below,
  1. APICoreDBContext dbContext;  
  2. public EmployeeService(APICoreDBContext _db)  
  3. {  
  4.    dbContext = _db;  
  5. }  
Now implement all the five methods that you have created in the above steps.
 
After implementing all the functions your file will look as below,
  1. using Microsoft.EntityFrameworkCore;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Threading.Tasks;  
  6. using WebAPICore.IServices;  
  7. using WebAPICore.Models;  
  8. namespace WebAPICore.Services {  
  9.     public class EmployeeService: IEmployeeService {  
  10.         APICoreDBContext dbContext;  
  11.         public EmployeeService(APICoreDBContext _db) {  
  12.             dbContext = _db;  
  13.         }  
  14.         public IEnumerable < Employee > GetEmployee() {  
  15.             var employee = dbContext.Employee.ToList();  
  16.             return employee;  
  17.         }  
  18.         public Employee AddEmployee(Employee employee) {  
  19.             if (employee != null) {  
  20.                 dbContext.Employee.Add(employee);  
  21.                 dbContext.SaveChanges();  
  22.                 return employee;  
  23.             }  
  24.             return null;  
  25.         }  
  26.         public Employee UpdateEmployee(Employee employee) {  
  27.             dbContext.Entry(employee).State = EntityState.Modified;  
  28.             dbContext.SaveChanges();  
  29.             return employee;  
  30.         }  
  31.         public Employee DeleteEmployee(int id) {  
  32.             var employee = dbContext.Employee.FirstOrDefault(x => x.Id == id);  
  33.             dbContext.Entry(employee).State = EntityState.Deleted;  
  34.             dbContext.SaveChanges();  
  35.             return employee;  
  36.         }  
  37.         public Employee GetEmployeeById(int id) {  
  38.             var employee = dbContext.Employee.FirstOrDefault(x => x.Id == id);  
  39.             return employee;  
  40.         }  
  41.     }  
  42. }  
Now Create the Controller, To do this Right-click on the Controllers folder then,
  • Choose "Add" Option then
  • Choose "Controller..." then
  • Select "API Controller - Empty" from the listed item then
  • Click on the "Add" button then
  • Provide the name to the controller as "EmployeeController.cs" and then
  • Click on the "Add" button
The controller will be created and now we have to write the API methods in it.

Now we need to create five APIs method in the controller.
 
Before adding the API method, we need to create an instance of the IEmployeeService interface and assign it by using the Constructor
so that we can call them to achieve our goal, to do this add the below lines,
  1. private readonly IEmployeeService employeeService;  
  2. public EmployeeController(IEmployeeService employee)  
  3. {  
  4.     employeeService = employee;  
  5. }  
After implementing all the five methods your controller file will look like as below,
  1. using System.Collections.Generic;  
  2. using Microsoft.AspNetCore.Mvc;  
  3. using WebAPICore.IServices;  
  4. using WebAPICore.Models;  
  5. namespace WebAPICore.Controllers {  
  6.     [Route("api/[controller]")]  
  7.     [ApiController]  
  8.     public class EmployeeController: ControllerBase {  
  9.         private readonly IEmployeeService employeeService;  
  10.         public EmployeeController(IEmployeeService employee) {  
  11.                 employeeService = employee;  
  12.             }  
  13.             [HttpGet]  
  14.             [Route("[action]")]  
  15.             [Route("api/Employee/GetEmployee")]  
  16.         public IEnumerable < Employee > GetEmployee() {  
  17.                 return employeeService.GetEmployee();  
  18.             }  
  19.             [HttpPost]  
  20.             [Route("[action]")]  
  21.             [Route("api/Employee/AddEmployee")]  
  22.         public Employee AddEmployee(Employee employee) {  
  23.                 return employeeService.AddEmployee(employee);  
  24.             }  
  25.             [HttpPut]  
  26.             [Route("[action]")]  
  27.             [Route("api/Employee/EditEmployee")]  
  28.         public Employee EditEmployee(Employee employee) {  
  29.                 return employeeService.UpdateEmployee(employee);  
  30.             }  
  31.             [HttpDelete]  
  32.             [Route("[action]")]  
  33.             [Route("api/Employee/DeleteEmployee")]  
  34.         public Employee DeleteEmployee(int id) {  
  35.                 return employeeService.DeleteEmployee(id);  
  36.             }  
  37.             [HttpGet]  
  38.             [Route("[action]")]  
  39.             [Route("api/Employee/GetEmployeeId")]  
  40.         public Employee GetEmployeeId(int id) {  
  41.             return employeeService.GetEmployeeById(id);  
  42.         }  
  43.     }  
  44. }  
After doing all the above work, your project structure will look like as below screenshot



That's it for this tutorial. I Have covered the How to create CORE API projects using Visual Studio 2019 and .Net Core Version 3.1.
 
We have created the Project Structure as we work in the realtime application and then created the Interface methods and those are the methods that are implemented into the service class. In the Controller, we have access to those all the methods.
 
I hope you enjoyed this tutorial. If you found this tutorial helpful then please like this tutorial -- that really motivates me to make more useful tutorials.
Next Recommended Reading Model Popup In ASP.NET Core 3.1