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

Introduction

In this article, we are going to create WEB API in ASP.Net core using Entity Framework Core’s Code first approach. In this, we are creating a simple CRUD operation of employees and test it using Swagger. In this API we are not going to use authentication, we will add this in my upcoming articles.

In this article,

  • Create ASP.Net Core Web API Project
  • Add Entity Framework and Create Tables
  • Create Service to perform CRUD Operation
  • Implement Service in Controller
  • Test API Using Swagger

Create ASP.Net Core Web API Project

Step 1

Open Visual Studio and create a new project. Here I am using Visual Studio 2019. You can use as per your system and requirements.

Step 2

Find and select Asp.Net Core Web API and then click on the Next button.

Create Asp.Net Core Web API with Entity Framework Code First Approach

Step 3

In the next wizard, you have to enter the following things and then click on the Next button

  • Project Name
  • Location of your project (Path where you want to save your project)

Create Asp.Net Core Web API with Entity Framework Code First Approach

Step 4

In this wizard screen, you have to specify the following things and then click on create button.

  • Target Framework, here I am using the current version installed in my system which is 5.
  • Authentication type: Currently in this project, we are not using authentication so here I select none.
  • Configure HTTPS: If you host your API with a secure HTTPS connection then you can check this box. It will add a redirection in your project which helps to redirect the http request to HTTPS automatically.
  • Enable Docker: For this project, we are not using docker so leave unchecked
  • Enable Open AI Support: If you want to implement Swagger in your project then you have to check this box. In this project, we are going to use a swagger so I check this box.

Create Asp.Net Core Web API with Entity Framework Code First Approach

Now your project is created and you can see the project structure in the below image. Remove extra files like weather controller and model if you don’t want it.

Add Entity Framework and Create Tables

For using the Entity Framework in our project and create a table using the code first approach we have to follow the below steps.

Step 1

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

Step 2

Install the Following NuGet Packages.

  • Microsoft.EntityFrameworkCore.SqlServer: This package is used to interact with SQL Server from our C# and .Net Core.
  • Microsoft.EntityFrameworkCore.Tools: This package is contained various commands like Add-Migration, Drop-Database, Get-DbContext, Get-Migration, Remove-Migration, Scaffold-DbContext, Script-Migration, Update-Database. In this article, we use Add-Migration and Update-Database commands.
  • Microsoft.Extensions.Configuration: Using this NuGet package we can read data from our app setting file. We will get our connection string from the app setting file.

Step 3

Now we add a new folder in our solution to contain various classes. For adding a new folder in our solution right click on project name the click on Add then click on New Folder and gave the name as Models.

Step 4

In this Models folder, we will use our entity classes. Right-click in this folder then Add then Class. Give a suitable name for your class.

Create Asp.Net Core Web API with Entity Framework Code First Approach

Step 5

Add fields as you want to create in your table. Here I create an Employee class with the following fields. Here key attribute defines that use this column as the primary key.

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

Now we create a context class which use as a middleware to SQL Server. Add a new class in your Models folder and add constructor and Employee DbSet as seen below code.

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

Step 7

Now we have to connect SQL Server with our project, for that, we need a connection string, and for this string, we are going to add the in-app setting file. Add your connection string as showing below.

Create Asp.Net Core Web API with Entity Framework Code First Approach

As see in the above code here I pass. (dot) as a server name because I used my local SQL Server. Then gave database name Tutorial, if this database does not exist then it will generate automatically. Here I have not given any username and password because I use windows authentication for this. If you want to use another method to login then pass username and password.

Step 8

Now we have to add Db Context in our startup file for this open startup file and add the following code.

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

In ConfigureService Method, we add our EmpContext class and pass connection string in it by getting from our appsetting file using Configure.GetConnectionString() method.

Step 9

Now open Package Manager Console by click on Tool Menu then NuGet Package Manager then Package Manager Console.

Step 10

Add the following command.

Add-Migration Init

Here Init is our name of migration, you can give as per your choice. Hit enter.

Step 11

As you can see in your solution new folder named Migration is created and in this project, there are two files. One is EmpContextModelSnapshot and another one is *_Init, here * mean date time stamp.

In this init file, there is the below code. This code executes when we use our next command and it will generate a new database and new table Called Employees.

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

For now, our database and table are not created to make changes in the Server-side use below command.

Update-Database

Now you can see in our SQL Server Employee table is created with the same fields as we add in our model.

Create Asp.Net Core Web API with Entity Framework Code First Approach

 Create New Response Model

To save and delete we are going to return a new model for send data to the user. To create a new folder called ViewModels In your solution because we want to store Entity classes and Other classes in a different place. Add a new class Called ResponseModel in this folder with the following properties as seen below code.

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

Create Service to perform CRUD Operation

In this project, we are going to use a repository pattern to interact with the database. We are not going to call the database in our controller, instead, we create a new service and call the database there. For this, we are going to create one interface and one class and then add dependency injection for these.

Step 1

Create an interface with the following methods as seen below code.

using ASPNetCoreWebAPiDemo.Models;
using ASPNetCoreWebAPiDemo.ViewModels;
using System.Collections.Generic;

namespace ASPNetCoreWebAPiDemo.Services
{
    public interface IEmployeeService
    {
        /// <summary>
        /// get list of all employees
        /// </summary>
        /// <returns></returns>
        List<Employees> GetEmployeesList();

        /// <summary>
        /// get employee details by employee id
        /// </summary>
        /// <param name="empId"></param>
        /// <returns></returns>
        Employees GetEmployeeDetailsById(int empId);

        /// <summary>
        ///  add edit employee
        /// </summary>
        /// <param name="employeeModel"></param>
        /// <returns></returns>
        ResponseModel SaveEmployee(Employees employeeModel);


        /// <summary>
        /// delete employees
        /// </summary>
        /// <param name="employeeId"></param>
        /// <returns></returns>
        ResponseModel DeleteEmployee(int employeeId);
    }
}

Step 2

Create a new class and implement the interface in this class.

Step 3

Now open your startup file and add the below line of code in ConfigurationService Method to add the dependency for our class and interface. This means when we call any method from this interface it will automatically call a method from the class.

services.AddScoped<IEmployeeService, EmployeeService>();

Constructor in Service

We are going to use DbContext in our service class for this we add dependency in the constructor as you can see in below code.

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

Get All Employees Method

/// <summary>
/// get list of all employees
/// </summary>
/// <returns></returns>
public List < Employees > GetEmployeesList() {
    List < Employees > empList;
    try {
        empList = _context.Set < Employees > ().ToList();
    } catch (Exception) {
        throw;
    }
    return empList;
}

In the above code, you can see that we are returning a list of employees from this method. To retrieve data from the database, we use the toList() method of DbContext.

Get Employee Details By Id Method

/// <summary>
/// get employee details by employee id
/// </summary>
/// <param name="empId"></param>
/// <returns></returns>
public Employees GetEmployeeDetailsById(int empId) {
    Employees emp;
    try {
        emp = _context.Find < Employees > (empId);
    } catch (Exception) {
        throw;
    }
    return emp;
}

In the above code, you can see that this method takes one parameter, ID. We get an employee object from the database which employee ID matches our parameter id.

Save Employee Method

/// <summary>
///  add edit employee
/// </summary>
/// <param name="employeeModel"></param>
/// <returns></returns>
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;
}

As you have seen in the above code, we take the employee model as a parameter. Then we called our get details by id method to get details of an employee by id and store In temp variable.

Here if employee Id is coming with a model which means we have to update the employee and if the employee id is null or zero then we have added a new employee.

If we got data in the temp variable then we assign new data from our parameter model and update employee context and with that, we also assign messages to our response model.

And if we got the temp variable is null, then we insert the parameter model as in context and pass the message in the response model.

In last, we called the save changes method of context to save all changes like insert update and set Is Success property of response model to true. If any error occurs, then we update is success to false and pass error message in message property.

Delete Employee Method

/// <summary>
/// delete employees
/// </summary>
/// <param name="employeeId"></param>
/// <returns></returns>
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;
}

In the delete method, we take employee id as a parameter. And call service method get detail by id forget employee details.

If an employee is found then we remove this employee by calling remove method of context, else we return the model with Employee not found message

Implement Service in Controller

Now our service is ready, so now we implement it in our controller.

Step 1

Add new controller by Right-click in Controllers folder then click in Add then Controller.

Create Asp.Net Core Web API with Entity Framework Code First Approach

Step 2

Now select API from the filter and select API Controller – Empty and click on Add button.

Create Asp.Net Core Web API with Entity Framework Code First Approach

Step 3

Now give an appropriate name and click on Add button.

 Create Asp.Net Core Web API with Entity Framework Code First Approach

Constructor Of Controller

In the Constructor of our controller, we implement dependency injection for our service.

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

For this controller, we are using routing with action methods. For example, if the user called Employee with Get method then it will call Get List Of All Employee Method and if the user called Employee/{id} with Get then it will call Get Employee Details By Id Method  and If user called Employee with POST method then it will call Save Employee Method and same as if the user called Employee with Delete method then it will call Delete Employee Method

Get List Of All Employee Method

/// <summary>
/// get all employess
/// </summary>
/// <returns></returns>
[HttpGet]
[Route("[action]")]
public IActionResult GetAllEmployees() {
    try {
        var employees = _employeeService.GetEmployeesList();
        if (employees == null) return NotFound();
        return Ok(employees);
    } catch (Exception) {
        return BadRequest();
    }
}

in the above method, we call a method from our service and assign it to the variable. If the variable is not null then we return ok status with this variable, else we return not found.

Get Employee Details By Id Method

/// <summary>
/// get employee details by id
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[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

/// <summary>
/// save employee
/// </summary>
/// <param name="employeeModel"></param>
/// <returns></returns>
[HttpPost]
[Route("[action]")]
public IActionResult SaveEmployees(Employees employeeModel) {
    try {
        var model = _employeeService.SaveEmployee(employeeModel);
        return Ok(model);
    } catch (Exception) {
        return BadRequest();
    }
}

Delete Employee Method

/// <summary>
/// delete employee  
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[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

While creating this project we added open AI support so when to run this project it will open the swagger page as seen below image. From here we can test our API.

Create Asp.Net Core Web API with Entity Framework Code First Approach

Add New Employee

Expand Save Employee Method and click on the try it now button. Now JSON fields are editable, to add data in the model as seen in below first image and click on execute. In the second image, you can see that data is updated in our table also.

Create Asp.Net Core Web API with Entity Framework Code First Approach

Update Existing Employee

In this request, we are passing the same model as we pass in the previous request but in the model, we pass id also.

Create Asp.Net Core Web API with Entity Framework Code First Approach

Get Employee Details By Id

Create Asp.Net Core Web API with Entity Framework Code First Approach

Get List of Employees

Create Asp.Net Core Web API with Entity Framework Code First Approach

Delete Employee

Create Asp.Net Core Web API with Entity Framework Code First Approach

If Employee Not Exist

Create Asp.Net Core Web API with Entity Framework Code First Approach

Conclusion

In this article, we create a simple Employee API with Entity Framework Core. In future articles, I implement authentication and also connect this API to Angular. So if you find this article helpful, kindly share it with your friends.