in ,

Construct a RESTful Internet API with ASP.NET Core 6 And EF Core


On this article, we are going to learn to create an internet API mission with ASP.NET Core 6 and entity framework core. Right here I will present you the best way to CRUD (Create, Learn, Replace and Delete) operations on an SQL server database desk utilizing the ASP.NET Core 6 REST API and Entity Framework Core. 

asp.web core 6 internet API tutorial, create an internet API with asp.web core and visible studio code, the best way to create internet API in asp.web core c# with database, construct asp.web core internet API – scratch to complete ( .web 6) free obtain,asp.web core internet API instance,asp.web core 6 internet API pattern mission GitHub, minimal API .web 6 crud instance, the best way to name internet API in asp.web core c#

Right here, I’ll take an instance of a Pupil Administration System, and carry out CRUD (Create, Learn, Replace and Delete) operations for College students and I will clarify the next factors listed on the requirement under for creating REST API with .web core 6 and entity framework core.

Requirement

  1. Create an internet API mission in .NET Core.
  2. Create a category for database context and mannequin for college students.
  3. Create a controller for college students with CRUD (Create, Learn, Replace and Delete) strategies.
  4. Create the Interface and Companies for the scholars.
  5. Set up Microsoft.EntityFrameworkCore.SqlServer from NuGet bundle supervisor.
  6. Handle database connection string in appsettings.json file.
  7. Name the created internet API with Postman.

Implementation

So Let’s begin with creating REST APIs with ASP.NET Core step-by-step.

Step 1

Open Visible Studio 2019 and click on on create a brand new mission as proven on the display under display. 

Visual Studio 2019

Step 2

Now, Whenever you click on on the Create New Mission, the next window will seem in your display as proven under, the place you must choose ASP.NET Core Internet Software after which click on on the Subsequent button.

ASP.NET Core Web Application

Step 3

Now, It’s important to select the title of your API mission in addition to the location of your mission as proven within the display under.

Create New Project

Step 4

Now you must choose the framework and its model, right here I’ve chosen ASP.NET Core 6, then choose the ASP.NET Core Internet API Mission from the mission record, after which click on on the create button.

Step 5

Now, you must create a desk for college students within 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 must create a brand new folder named Mannequin in your mission listing, after which create a category with the title Pupil underneath the created Mannequin folder as proven under.

Student Model

Step 7

Write the next properties on Pupil.cs Mannequin class.

Pupil. cs 

utilizing System.ComponentModel.DataAnnotations;
 
namespace Codingvila_REST_API.Mannequin
{
    public class Pupil
    {
        [Key]
        public int Student_Id { getset; }
        public int RollNo { getset; }
        public string EnrollmentNo { getset; }
        public string Identify { getset; }
        public string Department { getset; }
        public string College { getset; }
    }
}

Step 8

Now, you must obtain and set up Microsoft.EntityFrameworkCore.SqlServer NuGet bundle from the NuGet bundle supervisor.

Step 9

So, lets we create a database context to speak with the database and carry out the CRUD (Create, Learn, Replace and Delete) operations. Right here we are going to create a StudentContext as a database context in our mission for communication with the database.

Create the category named StudentContext.cs and drive it from the DbContext class, after which write the next code within the  StudentContext.cs class.

StudentContext.cs 

utilizing Codingvila_REST_API.Mannequin;
utilizing Microsoft.EntityFrameworkCore;
 
namespace Codingvila_REST_API
{
    public class StudentContext : DbContext
    {
        public StudentContext(DbContextOptions<StudentContext> choices) : base(choices)
        {
 
        }
        public DbSet<Pupil> College students { getset; }
    }
}

Step 10

Now, now we have to create a service for the scholars in addition to create an interface for the scholars and implement that interface within the created service. Right here we are going to create a new folder named StudentService and inside this folder, we are going to create two completely different courses first IStudentService.cs and the second is StudentService.cs the place IStudentService.cs is our interface and StudentService.cs is our service.

Write the next code into IStudentService.cs

 IStudentService.cs

utilizing Codingvila_REST_API.Mannequin;
utilizing System.Collections.Generic;
 
namespace Codingvila_REST_API.StudentService
{
    public interface IStudentService
    {
        Pupil CreateStudent(Pupil scholar);
        Record<Pupil> GetStudents();
        void UpdateStudent(Pupil worker);
        void DeleteStudent(int Id);
        Pupil GetStudent(int Id);
    }
}

Now, write the next code into StudentService.cs and derive it from the created interface IStudentService.

scholar companies.cs

utilizing Codingvila_REST_API.Mannequin;
utilizing System.Collections.Generic;
utilizing System.Linq;
 
namespace Codingvila_REST_API.StudentService
{
    public class StudentService : IStudentService
    {
        public StudentContext _studentDbContext;
        public StudentService(StudentContext StudentDbContext)
        {
            _studentDbContext = StudentDbContext;
        }
        public Pupil CreateStudent(Pupil Pupil)
        {
            _studentDbContext.College students.Add(Pupil);
            _studentDbContext.SaveChanges();
            return Pupil;
        }
        public Record<Pupil> GetStudents()
        {
            return _studentDbContext.College students.ToList();
        }
 
        public void UpdateStudent(Pupil Pupil)
        {
            _studentDbContext.College students.Replace(Pupil);
            _studentDbContext.SaveChanges();
        }
 
        public void DeleteStudent(int Id)
        {
            var Pupil = _studentDbContext.College students.FirstOrDefault(x => x.Student_Id == Id);
            if (Pupil != null)
            {
                _studentDbContext.Take away(Pupil);
                _studentDbContext.SaveChanges();
            }
        }
 
        public Pupil GetStudent(int Id)
        {
            return _studentDbContext.College students.FirstOrDefault(x => x.Student_Id == Id);
        }
    }
}

Step 11

Now, now we have to create a controller named StudentController throughout the controller folder accessible within the listing and write the next code into the controller class.

StudentController.cs

utilizing Codingvila_REST_API.Mannequin;
utilizing Codingvila_REST_API.StudentService;
utilizing Microsoft.AspNetCore.Mvc;
utilizing System.Collections.Generic;
 
namespace Codingvila_REST_API.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class StudentController : ControllerBase
    {
        personal readonly IStudentService _StudentService;
        public StudentController(IStudentService StudentService)
        {
            _StudentService = StudentService;
        }
 
        [HttpGet]
        [Route("[action]")]
        [Route("api/Student/GetStudents")]
        public IEnumerable<Pupil> GetStudents()
        {
            return _StudentService.GetStudents();
        }
 
        [HttpPost]
        [Route("[action]")]
        [Route("api/Student/CreateStudent")]
        public IActionResult CreateStudent(Pupil Pupil)
        {
            _StudentService.CreateStudent(Pupil);
            return Okay();
        }
 
        [HttpPost]
        [Route("[action]")]
        [Route("api/Student/UpdateStudent")]
        public IActionResult UpdateStudent(Pupil Pupil)
        {
            _StudentService.UpdateStudent(Pupil);
            return Okay();
        }
 
        [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 Okay();
            }
            return NotFound($"Pupil Not Discovered with ID : {existingStudent.Student_Id}");
        }
 
        [HttpGet]
        [Route("GetStudent")]
        public Pupil GetStudent(int id)
        {
            return _StudentService.GetStudent(id);
        }
    }
}

Step 12

Now, write our database connection string into the appsettings.json file.

appsettings.json

{
  "ConnectionStrings": {
    "DatabaseConnectionString""Information Supply=NIKUNJSATASIYASQLEXPRESS;Preliminary Catalog=dbCodingvila;Built-in Safety=True"
  },
  "Logging": {
    "LogLevel": {
      "Default""Info",
      "Microsoft""Warning",
      "Microsoft.Internet hosting.Lifetime""Info"
    }
  },
  "AllowedHosts""*"
}

Step 13

Now, for the dependency of companies and database, now we have so as to add a database connection into the startup file Startup. cs.

Within the Startup.cs file, throughout the ConfigureServices methodology, add the next code 

Startup. cs

public void ConfigureServices(IServiceCollection companies)
{
 
    companies.AddControllers();
    companies.AddDbContextPool<StudentContext>(choices =>
    choices.UseSqlServer(Configuration.GetConnectionString("DatabaseConnectionString")));
    companies.AddScoped<StudentService.IStudentService, StudentService.StudentService>();
 
    companies.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1"new OpenApiInfo { Title = "Codingvila_REST_API", Model = "v1" });
    });
}

Step 14

Now, we’re prepared will all adjustments and configurations, you may run your API mission, open postman, and check the created service as proven under.

API for Create Student

Abstract

On this article, we realized the way in which to create an internet API for CRUD functions with ASP.NET Core 6 and entity framework core in addition to in regards to the mannequin, interface, companies and and so forth.

Tags:

asp.web core internet api instance

asp.web core internet api tutorial

the best way to create internet api in asp.web core c# with database

eat internet api in asp.web core mvc (step-by-step mission)

the best way to name internet api in asp.web core c#

.web core relaxation api tutorial

internet api vs relaxation api

internet api instance c#



Supply hyperlink

What do you think?

Written by admin

Laisser un commentaire

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *

GIPHY App Key not set. Please check settings

Yellow Field Sandals simply $17.99 + Free Delivery!

YouTube Revamps Associate Program Re-Utility Insurance policies