Build a RESTful Web API with ASP.NET Core 6 And EF Core

watch_later 2/22/2023

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. 

asp.net core 6 web API tutorial, create a web API with asp.net core and visual studio code, how to create web API in asp.net core c# with database, build asp.net core web API - scratch to finish ( .net 6) free download,asp.net core web API example,asp.net core 6 web API sample project GitHub, minimal API .net 6 crud example, how to call web API in asp.net core c#

Create REST API with ASP.NET Core 5.0 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

  1. Create a web API project in .NET Core.
  2. Create a class for database context and model for students.
  3. Create a controller for students with CRUD (Create, Read, Update and Delete) methods.
  4. Create the Interface and Services for the students.
  5. Install Microsoft.EntityFrameworkCore.SqlServer from NuGet package manager.
  6. Manage database connection string in appsettings.json file.
  7. 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. 

Visual Studio 2019

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.

ASP.NET Core Web Application

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.

Create New Project

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.

Student Model

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 { getset; }
        public int RollNo { getset; }
        public string EnrollmentNo { getset; }
        public string Name { getset; }
        public string Branch { getset; }
        public string University { getset; }
    }
}

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 { getset; }
    }
}

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.

API for Create Student

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.

Tags:

asp.net core web api example
asp.net core web api tutorial
how to create web api in asp.net core c# with database
consume web api in asp.net core mvc (step by step project)
how to call web api in asp.net core c#
.net core rest api tutorial
web api vs rest api
web api example c#

Codingvila provides articles and blogs on web and software development for beginners as well as free Academic projects for final year students in Asp.Net, MVC, C#, Vb.Net, SQL Server, Angular Js, Android, PHP, Java, Python, Desktop Software Application and etc.

Thank you for your valuable time, to read this article, If you like this article, please share this article and post your valuable comments.

Once, you post your comment, we will review your posted comment and publish it. It may take a time around 24 business working hours.

Sometimes I not able to give detailed level explanation for your questions or comments, if you want detailed explanation, your can mansion your contact email id along with your question or you can do select given checkbox "Notify me" the time of write comment. So we can drop mail to you.

If you have any questions regarding this article/blog you can contact us on info.codingvila@gmail.com

sentiment_satisfied Emoticon