Create ASP.NET Core Web API with Entity Framework Core Code First Approach

Build a simple ASP.NET Core Web API with Entity Framework Core Code First, including the model, DbContext, service layer, controller actions, and Swagger testing.

Create ASP.NET Core Web API with Entity Framework Core Code First Approach cover

Introduction

In this article, we are going to create a Web API in ASP.NET Core using Entity Framework Core's Code First approach. The sample API performs basic CRUD operations for employees and tests them using Swagger. Authentication is not included in this article.

In This Article

  • Create ASP.NET Core Web API project
  • Add Entity Framework and create tables
  • Create a service to perform CRUD operations
  • Implement the service in the controller
  • Test the API using Swagger

Create ASP.NET Core Web API Project

Step 1

Open Visual Studio and create a new project. The original article used Visual Studio 2019.

Step 2

Select ASP.NET Core Web API and click Next.

Select ASP.NET Core Web API

Step 3

Enter the project name and location, then click Next.

Project name and location

Step 4

Choose the framework and project options, then click Create.

The article used:

  • Target Framework: .NET 5
  • Authentication Type: None
  • Configure HTTPS: enabled
  • Enable Docker: disabled
  • Enable OpenAPI Support: enabled

Project configuration

The project structure should now be created. Remove the default WeatherForecast controller and model if you do not need them.

Project structure

Add Entity Framework and Create Tables

To use Entity Framework in the project and create tables with the Code First approach, follow these steps.

Step 1

Right-click the project name and open Manage NuGet Packages.

Manage NuGet Packages

Step 2

Install the following NuGet packages:

  • Microsoft.EntityFrameworkCore.SqlServer: used to interact with SQL Server from C# and .NET Core
  • Microsoft.EntityFrameworkCore.Tools: provides commands like Add-Migration and Update-Database
  • Microsoft.Extensions.Configuration: used to read the connection string from appsettings

Step 3

Create a folder named Models to hold the entity classes.

Create Models folder

Step 4

Add a class inside the Models folder.

Add class to Models folder

Step 5

Add the fields you want in the table. The example uses an Employees class.

public class Employees { [Key] public int EmployeeId { get; set; } public string EmployeeFirstName { get; set; } public string EmployeeLastName { get; set; } public decimal Salary { get; set; } public string Designation { get; set; } }

Step 6

Create a context class to communicate with SQL Server.

public class EmpContext : DbContext { public EmpContext(DbContextOptions options) : base(options) { } DbSet<Employees> Employees { get; set; } }

Step 7

Add the connection string to appsettings.

Add connection string

The article uses a local SQL Server connection and Windows authentication.

Step 8

Register the DbContext in Startup.

services.AddDbContext<EmpContext>(x => x.UseSqlServer(Configuration.GetConnectionString("ConStr")));

Step 9

Open Package Manager Console from the Tools menu.

Open Package Manager Console

Step 10

Run the migration command.

Add-Migration Init

Step 11

A Migrations folder will be created. It contains the model snapshot and the migration file.

Migration files

The generated migration creates the Employees table.

using Microsoft.EntityFrameworkCore.Migrations; namespace ASPNetCoreWebAPiDemo.Migrations { public partial class Init : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "Employees", columns: table => new { EmployeeId = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), EmployeeFirstName = table.Column<string>(type: "nvarchar(max)", nullable: true), EmployeeLastName = table.Column<string>(type: "nvarchar(max)", nullable: true), Salary = table.Column<decimal>(type: "decimal(18,2)", nullable: false), Designation = table.Column<string>(type: "nvarchar(max)", nullable: true) }, constraints: table => { table.PrimaryKey("PK_Employees", x => x.EmployeeId); }); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "Employees"); } } }

Step 12

Apply the migration to create the database and table.

Update-Database

Update database

The Employees table is now created in SQL Server.

Employees table created

Create New Response Model

For save and delete operations, the article returns a response model.

public class ResponseModel { public bool IsSuccess { get; set; } public string Messsage { get; set; } }

Create Service to Perform CRUD Operation

The project uses the repository pattern, so the database access is moved into a service instead of the controller.

Step 1

Create an interface with the following methods.

using ASPNetCoreWebAPiDemo.Models; using ASPNetCoreWebAPiDemo.ViewModels; using System.Collections.Generic; namespace ASPNetCoreWebAPiDemo.Services { public interface IEmployeeService { List<Employees> GetEmployeesList(); Employees GetEmployeeDetailsById(int empId); ResponseModel SaveEmployee(Employees employeeModel); ResponseModel DeleteEmployee(int employeeId); } }

Step 2

Create a class that implements the interface.

Step 3

Register the service in Startup.

services.AddScoped<IEmployeeService, EmployeeService>();

Service Constructor

private EmpContext _context; public EmployeeService(EmpContext context) { _context = context; }

Get All Employees Method

public List<Employees> GetEmployeesList() { List<Employees> empList; try { empList = _context.Set<Employees>().ToList(); } catch (Exception) { throw; } return empList; }

This method returns all employees from the database.

Get Employee Details By Id Method

public Employees GetEmployeeDetailsById(int empId) { Employees emp; try { emp = _context.Find<Employees>(empId); } catch (Exception) { throw; } return emp; }

Save Employee Method

public ResponseModel SaveEmployee(Employees employeeModel) { ResponseModel model = new ResponseModel(); try { Employees _temp = GetEmployeeDetailsById(employeeModel.EmployeeId); if (_temp != null) { _temp.Designation = employeeModel.Designation; _temp.EmployeeFirstName = employeeModel.EmployeeFirstName; _temp.EmployeeLastName = employeeModel.EmployeeLastName; _temp.Salary = employeeModel.Salary; _context.Update<Employees>(_temp); model.Messsage = "Employee Update Successfully"; } else { _context.Add<Employees>(employeeModel); model.Messsage = "Employee Inserted Successfully"; } _context.SaveChanges(); model.IsSuccess = true; } catch (Exception ex) { model.IsSuccess = false; model.Messsage = "Error : " + ex.Message; } return model; }

If the employee exists, the code updates it; otherwise, it inserts a new record.

Delete Employee Method

public ResponseModel DeleteEmployee(int employeeId) { ResponseModel model = new ResponseModel(); try { Employees _temp = GetEmployeeDetailsById(employeeId); if (_temp != null) { _context.Remove<Employees>(_temp); _context.SaveChanges(); model.IsSuccess = true; model.Messsage = "Employee Deleted Successfully"; } else { model.IsSuccess = false; model.Messsage = "Employee Not Found"; } } catch (Exception ex) { model.IsSuccess = false; model.Messsage = "Error : " + ex.Message; } return model; }

Implement Service in Controller

Now that the service is ready, implement it in the controller.

Step 1

Add a new controller under the Controllers folder.

Add controller

Step 2

Choose API, then API Controller - Empty.

API controller template

Step 3

Give the controller a name and click Add.

Name the controller

Controller Constructor

IEmployeeService _employeeService; public EmployeeController(IEmployeeService service) { _employeeService = service; }

The controller uses route-based action methods:

  • Employee with GET calls the list method
  • Employee/{id} with GET calls the details method
  • Employee with POST calls the save method
  • Employee with DELETE calls the delete method

Get List Of All Employee Method

[HttpGet] [Route("[action]")] public IActionResult GetAllEmployees() { try { var employees = _employeeService.GetEmployeesList(); if (employees == null) return NotFound(); return Ok(employees); } catch (Exception) { return BadRequest(); } }

Get Employee Details By Id Method

[HttpGet] [Route("[action]/id")] public IActionResult GetEmployeesById(int id) { try { var employees = _employeeService.GetEmployeeDetailsById(id); if (employees == null) return NotFound(); return Ok(employees); } catch (Exception) { return BadRequest(); } }

Save Employee Method

[HttpPost] [Route("[action]")] public IActionResult SaveEmployees(Employees employeeModel) { try { var model = _employeeService.SaveEmployee(employeeModel); return Ok(model); } catch (Exception) { return BadRequest(); } }

Delete Employee Method

[HttpDelete] [Route("[action]")] public IActionResult DeleteEmployee(int id) { try { var model = _employeeService.DeleteEmployee(id); return Ok(model); } catch (Exception) { return BadRequest(); } }

Test API Using Swagger

Because OpenAPI support was enabled during project creation, the application opens Swagger when it runs.

Swagger UI

Add New Employee

Expand the Save Employee method, click Try it out, enter the JSON payload, and execute the request.

Add employee request

Employee added to table

Update Existing Employee

Include the employee id in the model and send the same payload again.

Update employee request

Updated employee result

Get Employee Details By Id

Get employee by id

Get List of Employees

Get employee list

Get employee list response

Delete Employee

Delete employee request

Delete employee response

If Employee Does Not Exist

Employee not found

Conclusion

In this article, we built a simple Employee API with Entity Framework Core. In future articles, the original author planned to add authentication and connect the API to Angular.