In this article, we will learn how to create a web API project with ASP.NET Core 6 and entity framework core. Here I'll show you how to CRUD (Create, Read, Update and Delete) operations on an SQL server database table using the ASP.NET Core 6 REST API and Entity Framework Core.
Here, I will take an example of a Student Management System, and perform CRUD (Create, Read, Update and Delete) operations for Students and I'll explain the following points listed on the requirement below for creating REST API with .net core 6 and entity framework core.
Requirement
- Create a web API project in .NET Core.
- Create a class for database context and model for students.
- Create a controller for students with CRUD (Create, Read, Update and Delete) methods.
- Create the Interface and Services for the students.
- Install Microsoft.EntityFrameworkCore.SqlServer from NuGet package manager.
- Manage database connection string in appsettings.json file.
- Call the created web API with Postman.
Implementation
So Let's start with creating REST APIs with ASP.NET Core step by step.
Step 1
Open Visual Studio 2019 and click on create a new project as shown on the screen below screen.
Step 2
Now, When you click on the Create New Project, the following window will appear on your screen as shown below, where you have to select ASP.NET Core Web Application and then click on the Next button.
Step 3
Now, You have to choose the name of your API project as well as the location of your project as shown in the screen below.
Step 4
Now you have to select the framework and its version, here I have selected ASP.NET Core 6, then select the ASP.NET Core Web API Project from the project list, and then click on the create button.
Step 5
Now, you have to create a table for students in the SQL server database.
CREATE TABLE [dbo].[Students]( [Student_Id] [int] IDENTITY(1,1) NOT NULL, [RollNo] [int] NULL, [EnrollmentNo] [nvarchar](15) NULL, [Name] [nvarchar](50) NULL, [Branch] [nvarchar](50) NULL, [University] [nvarchar](50) NULL ) ON [PRIMARY]
Step 6
Now, you have to create a new folder named Model in your project directory, and then create a class with the name Student under the created Model folder as shown below.
Step 7
Write the following properties on Student.cs Model class.
Student. cs
using System.ComponentModel.DataAnnotations; namespace Codingvila_REST_API.Model { public class Student { [Key] public int Student_Id { get; set; } public int RollNo { get; set; } public string EnrollmentNo { get; set; } public string Name { get; set; } public string Branch { get; set; } public string University { get; set; } } }
Step 8
Now, you have to download and install Microsoft.EntityFrameworkCore.SqlServer NuGet package from the NuGet package manager.
Step 9
So, lets we create a database context to communicate with the database and perform the CRUD (Create, Read, Update and Delete) operations. Here we will create a StudentContext as a database context in our project for communication with the database.
Create the class named StudentContext.cs and drive it from the DbContext class, and then write the following code in the StudentContext.cs class.
StudentContext.cs
using Codingvila_REST_API.Model; using Microsoft.EntityFrameworkCore; namespace Codingvila_REST_API { public class StudentContext : DbContext { public StudentContext(DbContextOptions<StudentContext> options) : base(options) { } public DbSet<Student> Students { get; set; } } }
Step 10
Now, we have to create a service for the students as well as create an interface for the students and implement that interface in the created service. Here we will create a new folder named StudentService and within this folder, we will create two different classes first IStudentService.cs and the second is StudentService.cs where IStudentService.cs is our interface and StudentService.cs is our service.
Write the following code into IStudentService.cs
IStudentService.cs
using Codingvila_REST_API.Model; using System.Collections.Generic; namespace Codingvila_REST_API.StudentService { public interface IStudentService { Student CreateStudent(Student student); List<Student> GetStudents(); void UpdateStudent(Student employee); void DeleteStudent(int Id); Student GetStudent(int Id); } }
Now, write the following code into StudentService.cs and derive it from the created interface IStudentService.
student services.cs
using Codingvila_REST_API.Model; using System.Collections.Generic; using System.Linq; namespace Codingvila_REST_API.StudentService { public class StudentService : IStudentService { public StudentContext _studentDbContext; public StudentService(StudentContext StudentDbContext) { _studentDbContext = StudentDbContext; } public Student CreateStudent(Student Student) { _studentDbContext.Students.Add(Student); _studentDbContext.SaveChanges(); return Student; } public List<Student> GetStudents() { return _studentDbContext.Students.ToList(); } public void UpdateStudent(Student Student) { _studentDbContext.Students.Update(Student); _studentDbContext.SaveChanges(); } public void DeleteStudent(int Id) { var Student = _studentDbContext.Students.FirstOrDefault(x => x.Student_Id == Id); if (Student != null) { _studentDbContext.Remove(Student); _studentDbContext.SaveChanges(); } } public Student GetStudent(int Id) { return _studentDbContext.Students.FirstOrDefault(x => x.Student_Id == Id); } } }
Step 11
Now, we have to create a controller named StudentController within the controller folder available in the directory and write the following code into the controller class.
StudentController.cs
using Codingvila_REST_API.Model; using Codingvila_REST_API.StudentService; using Microsoft.AspNetCore.Mvc; using System.Collections.Generic; namespace Codingvila_REST_API.Controllers { [Route("api/[controller]")] [ApiController] public class StudentController : ControllerBase { private readonly IStudentService _StudentService; public StudentController(IStudentService StudentService) { _StudentService = StudentService; } [HttpGet] [Route("[action]")] [Route("api/Student/GetStudents")] public IEnumerable<Student> GetStudents() { return _StudentService.GetStudents(); } [HttpPost] [Route("[action]")] [Route("api/Student/CreateStudent")] public IActionResult CreateStudent(Student Student) { _StudentService.CreateStudent(Student); return Ok(); } [HttpPost] [Route("[action]")] [Route("api/Student/UpdateStudent")] public IActionResult UpdateStudent(Student Student) { _StudentService.UpdateStudent(Student); return Ok(); } [HttpDelete] [Route("[action]")] [Route("api/Student/DeleteStudent")] public IActionResult DeleteStudent(int id) { var existingStudent = _StudentService.GetStudent(id); if (existingStudent != null) { _StudentService.DeleteStudent(existingStudent.Student_Id); return Ok(); } return NotFound($"Student Not Found with ID : {existingStudent.Student_Id}"); } [HttpGet] [Route("GetStudent")] public Student GetStudent(int id) { return _StudentService.GetStudent(id); } } }
Step 12
Now, write our database connection string into the appsettings.json file.
appsettings.json
{ "ConnectionStrings": { "DatabaseConnectionString": "Data Source=NIKUNJSATASIYA\\SQLEXPRESS;Initial Catalog=dbCodingvila;Integrated Security=True" }, "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } }, "AllowedHosts": "*" }
Step 13
Now, for the dependency of services and database, we have to add a database connection into the startup file Startup. cs.
In the Startup.cs file, within the ConfigureServices method, add the following code
Startup. cs
public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddDbContextPool<StudentContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DatabaseConnectionString"))); services.AddScoped<StudentService.IStudentService, StudentService.StudentService>(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "Codingvila_REST_API", Version = "v1" }); }); }
Step 14
Now, we are ready will all changes and configurations, you can run your API project, open postman, and test the created service as shown below.
Summary
In this article, we learned the way to create a web API for CRUD applications with ASP.NET Core 6 and entity framework core as well as about the model, interface, services and etc.