In this article, I will show how to create .NET Core API using Entity Framework Code First Approach. I will develop Student Web API application with basic operation.

For more updates please do Subscribe via Email:

I. .NET Core API

A .NET Core API is a opensource newly technology by Microsoft. API is an application programming interface is a connection between computers or between computer programs. It is a type of software interface, offering a service to other pieces of software. A document or standard that describes how to build or use such a connection or interface is called an API specification.

II. HTTP Verbs

This are commonly used HTTP Verbs are (POST, GET, PUT, PATCH, and DELETE ) this response to Create, Read, Update and Delete (CRUD) request operation.

III. Requirements

  • VS Code or Microsoft Visual Studio
  • MSSQL

In this part I’ll used Microsoft Visual Studio 2019 to create this API application.

IV. Create Application

First open the Visual Studio and select “Create a new project“.

Next Search “Core API” and select ASP.NET Core Web API using C# programming language. then Next

  • Configure your new project

this part you can configure your application according your project design. now this application is tutorial purpose only so that I will name the application as “StudentInfoAPI” and Location is the path of the generated code local where is stored. and the solution name you can change it but for me I will name it same as Project name as will. Then Next

Here is the additional information of your configuration above. You can select Target Framework according to your project design. but in this project I will choose “.NET 5.0” the latest version of .NET.

And also I choose “None” in authentication type because we are not taking about authentication here, I will create separate article about that. and also HTTPS and Docker I will not enable this part and I will create separate article about that. What I will do now is create a basic and simple API for student.

After all then just click Create in Right part to create the application.

And this is the file here in Solution Explorer.

V. Create Models

Now I will create a Folder name “Models” where I put models and DBContext to connect Database.

Just right click the Project Solution -> ADD -> New Folder.

And now I will create student model inside the Models folder.

To add just Right Click the Models folders; Models->Add->Class.

Select class and name it Student then click Add button.

Class Models

This is the simple Class models. you can create the database design using this, In this basic model the Database automatics generate the table and columns by default configuration.

public class Student
    {
        public int StudentID { get; set; }
        public string S_FirstName { get; set; }
        public string S_LastName { get; set; }
        public string S_MiddleName { get; set; }
        public string StudentLevel { get; set; }
        public string StudentContacts { get; set; }
        public string StudentEmail { get; set; }
        public DateTime TDT { get; set; }
        public DateTime UDT { get; set; }
    }

But you can configure it but doing this.

[Key] – is introduce to SQL that this field is a Primary Key.

[Required] – is introduce to SQL also that this field is a required and not null.

[Column(TypeName = “varchar(50)”)] – this is also introduce the the type of column is a “Varchar” and the length is 50.

for more, your can explore it using this guide. keep coding and Enjoy.

using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace StudentInfoAPI.Models
{
    public class Student
    {
        [Key]
        public int StudentID { get; set; }
        [Required]
        [Column(TypeName = "varchar(50)")]
        public string S_FirstName { get; set; }
        [Required]
        [Column(TypeName = "varchar(50)")]
        public string S_LastName { get; set; }
        [Column(TypeName = "varchar(50)")]
        public string S_MiddleName { get; set; }
        public int StudentLevel { get; set; }
        [Column(TypeName = "varchar(50)")]
        public string StudentContacts { get; set; }
        [Column(TypeName = "varchar(50)")]
        public string StudentEmail { get; set; }
        public DateTime TDT { get; set; }
        public DateTime UDT { get; set; }
    }
}

VI. Create DbContext

Now I will create DB Context in same folder inside the “Models”.

If you are facing error during creating the DbContext link this. you can install the package.

Or Here just go to Nuget packages and install the packages.

  • DBContext
using Microsoft.EntityFrameworkCore;
namespace StudentInfoAPI.Models
{
    public class StudentDBContext : DbContext
    {
        public StudentDBContext(DbContextOptions<StudentDBContext> options): base(options)
            {
            }
       public DbSet<Student> students { get; set; }
    }
}

VII. Setup SQL Connection

To set up the connection String, go to appsettings.json and put the connection string . please see image below.

Then go to startup.cs and do some configuration, please see image below.

VIII. Add Migration

To Add migration you need to execute this command;

Add-Migration -context StudentDBContext

by using this command, before executing it CLI asking for name of migration.

but you can do it like this. by simply add the name of migration so that the CLI run it without asking any because you putting the name in the command.

PM> Add-migration StudentMigration -context StudentDBContext

XI. Update Database

by create or updating the SQL database using migration.

  • Run this Command: this command run all available DBContext migration in your application.
Update-Database
  • you can run specific migration by doing like this. this is applicable if you have make table and adding/updating database one by one.
 Update-Database -context StudentDBContext

X. Database

here is it. just compare the created table in SQL and also our model class properties.

XI. Create API Controller

Again right click the “Controller” and add then Controller.

Select API and API Controller with actions, using EF and then Add.

Select Model and DBContext for context class. and Add.

API Controller

using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using StudentInfoAPI.Models;
namespace StudentInfoAPI.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class StudentsController : ControllerBase
    {
        private readonly StudentDBContext _context;
        public StudentsController(StudentDBContext context)
        {
            _context = context;
        }
        // GET: api/Students
        [HttpGet]
        public async Task<ActionResult<IEnumerable<Student>>> Getstudents()
        {
            return await _context.students.ToListAsync();
        }
        // GET: api/Students/5
        [HttpGet("{id}")]
        public async Task<ActionResult<Student>> GetStudent(int id)
        {
            var student = await _context.students.FindAsync(id);
            if (student == null)
            {
                return NotFound();
            }
            return student;
        }
        // PUT: api/Students/5
        // To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
        [HttpPut("{id}")]
        public async Task<IActionResult> PutStudent(int id, Student student)
        {
            if (id != student.StudentID)
            {
                return BadRequest();
            }
            _context.Entry(student).State = EntityState.Modified;
            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!StudentExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }
            return NoContent();
        }
        // POST: api/Students
        // To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
        [HttpPost]
        public async Task<ActionResult<Student>> PostStudent(Student student)
        {
            _context.students.Add(student);
            await _context.SaveChangesAsync();
            return CreatedAtAction("GetStudent", new { id = student.StudentID }, student);
        }
        // DELETE: api/Students/5
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteStudent(int id)
        {
            var student = await _context.students.FindAsync(id);
            if (student == null)
            {
                return NotFound();
            }
            _context.students.Remove(student);
            await _context.SaveChangesAsync();
            return NoContent();
        }
        private bool StudentExists(int id)
        {
            return _context.students.Any(e => e.StudentID == id);
        }
    }
}

Web View by swagger

Thank you for visiting my website blog/article. please do subscribe to be updated once I have new post topics.

One Reply to “.NET Core API using Entity Framework (EF) Code First Approach”

Leave a Reply

Your email address will not be published. Required fields are marked *