Date:

Share:

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

Related Articles

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 will show you how to perform CRUD operations (create, read, update and delete) in a SQL Server database table using ASP.NET Core 5.0 REST API and Entity Framework Core.

Here I will take an example of a student management system, and perform CRUD operations (create, read, update and delete) for students and explain the following points detailed in the requirement below to create a REST API with .net core 5.0 and an entity framework core.

demand

  1. Create a Web API project in .NET Core.
  2. Create a classroom for the context of a database and model for students.
  3. Create student visits with CRUD methods (create, read, update and delete).
  4. Create the interface and services for students.
  5. install Microsoft.EntityFrameworkCore.SqlServer From the NuGet package manager.
  6. Manage a database connection string in the appsettings.json file.
  7. Call the Web API created with Postman.

Implementation

So let’s start by creating REST APIs with ASP.NET Core step by step.

Level 1

Open Visual Studio 2019 and click Create New Project as shown in the screen below the screen.

Visual Studio 2019

level2

Now, when you click on Create a new project, The following window will appear on your screen as shown below, which you must select ASP.NET Core Web Application And then press the next button.

ASP.NET Core Web Application

Step 3

Now, you need to select the There Of your API project as well as a place Of your project as shown in the screen below.

Create a new project

Step 4

Now you have to choose the frame and its version, here I have chosen ASP.NET Core 5.0, And then select ASP.NET Core Web API Project from the list of projects and then click to create Button as shown on the screen.

ASP.NET Core Web API

Step 5

Now, you need to create a table for students in a 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 need to create a new folder named model Into your project directory, and then Create a class with the name Student Under the Model folder created as shown below.

Student model

Step 7

Write the following characteristics in the 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 need to download and install Microsoft.EntityFrameworkCore.SqlServer NuGet package from NuGet Package Manager As shown on the screen.

Microsoft EntityFramework Core SQL Server

Step 9

So, allows us to contact the database to communicate with the database and perform the CRUD operations (create, read, update and delete). Here we will create a Student contact As the context of a database in our project to communicate with the database.

Create the class named StudentContext.cs and move it from the DbContext Class, and then write the following code in StudentContext.cs status.

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 need to create a service for the students as well as create an interface for the students and apply that interface in the created service. Here we will create wa A new folder called StudentService And within this folder we will first create two different classes ISstudentService.cs And the other is StudentService.cs Where IStudentService.cs is our interface and StudentService.cs is our service.

Write the following code into ISstudentService.cs

ISstudentService.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 extract it from the created interface ISstudentService.

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 need to create a controller named Student Comptroller Inside the controller folder available in the directory and write the following code to 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 the string connecting our database into appssettings.json file.

appssettings.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, in order to depend on the services and the database, we need to add a database connection to the Startup.cs executable file.

In the Startup.cs file, inside 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 if all the changes and configurations, you will be able to run your API project, open the postman and check the service created as shown below.

API for Create Student

Summary

In this article we learned about creating a web API for CRUD applications with ASP.NET Core 5.0 and Entity framework, as well as on the model, interface, services, etc.

.

Source

Popular Articles