Create REST API with ASP.NET Core 5.0 And Entity Framework Core

watch_later 07 May, 2021
comment 1 Comment

In this article, we will learn how to create a web API project with ASP.NET Core 5.0 and entity framework core. Here I'll show you how to CRUD (Create, Read, Update and Delete) operations on SQL server database table using the ASP.NET Core 5.0 REST API and Entity Framework Core. 

Create REST API with ASP.NET Core 5.0 And Entity Framework Core

Here, I will take an example of 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 5.0 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 the 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 5.0, and then select the ASP.NET Core Web API Project from the project list and then click on the create button as shown in the screen.

ASP.NET Core Web API

Step 5

Now, you have to create a table for students in 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 into 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 as shown on the screen.

Microsoft EntityFramework Core SQL Server

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 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 creating an interface for the students and implement that interface in the created service. Here we will create and 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.

StudentService.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 following code into 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 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 dependency of services and database we have to add database connection into startup file Startup.cs.

In the Startup.cs file, within ConfigureServices method add 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 way to create a web API for CRUD application with ASP.NET Core 5.0 and entity framework core as well as about the model, interface, services and etc.

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.

avatar

Hi. Thanks for this tutorial. I was able to copy and create my own API running on Azure. However on the swagger page, it seems I get duplicates, and I'm not sure why.

For example:

GET
​/api​/Air​/GetAirRecords
GET
​/api​/Air​/api​/Air​/GetAirRecords

Both seem to work - which is nice. But I wonder why the second entry 'api/Air/api/Air' ?

Best regards.

delete August 23, 2021 at 7:03 PM

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