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 added this in my upcoming articles.

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


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 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 next button.

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


Step 3

In next wizard you have to enter following things and then click on 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 Core Code First Approach - YogeshHadiya.in


Step 4

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

  • Target Framework, Here I am using current version install 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 secure https connection then you can check this box. It will add redirection in your project which help to redirect http request to https automatically.
  • Enable Docker: For this project we are not using docker so leave un check
  • 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 swagger so I check this box.
Create Asp.Net Core Web API with Entity Framework Core Code First Approach - YogeshHadiya.in


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

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


Add Entity Framework and Create Tables

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

Step 1

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

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


Step 2

Install the Following NuGet Packages.

  • Microsoft.EntityFrameworkCore.SqlServer : This Package is use for interact with SQL Server from Our C# and .Net Core.
  • Microsoft.EntityFrameworkCore.Tools : This package is contained various command 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 Upadate-Database command.
  • 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 new folder in our solution right click on project name the click on Add then click on New Folder and gave name as Models.

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


Step 4

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

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


Step 5

Add fields as you want to create in your table. Here I create Employee class with following fields. Here key attribute define that use this column as 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; }
}
C#

Step 6

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

public class EmpContext : DbContext
{
    public EmpContext(DbContextOptions options) : base(options)
    {

    }
    DbSet<Employees> Employees { get; set; }
}
C#

Step 7

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

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


As see in above code here I pass . (dot) as a server name because I used my local pc SQL Server. Then gave database name Tutorial, if this database not exist then it will generate automatically. Here I not give any username and password because I use windows authentication for this if you want to use other 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 following code.

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

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.

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


Step 10

Add 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 is two file. One is EmpContextModelSnapshot and other one is *_Init , here * mean date time stamp.

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


In this init file, there is below code. This code execute when we use our next command and it will generate 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");
        }
    }
}
C#

Step 12

For now, our database and table is not created for make changes in Server side use below command.

Update-Database

 

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


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

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


 

 Create New Response Model

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

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

 

Create Service to perform CRUD Operation

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


Step 1

Create interface with following methods as seen in 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);
    }
}
C#

Step 2

Create new class and implement interface in this class.

Step 3

Now open your startup file and add below line of code in ConfigurationService Method to add 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>();
C#

 

Constructor in Service

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

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

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;
}
C#

In the above code, you can see that we are return list of employees from this method. For retrieve data from database, we use 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;
}
C#

In the above, you can see that this method take one parameter, ID. We get employee object from database which employee ID match to 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;
}
C#

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

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

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

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

In last, we called 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 occur, 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;
}
C#

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

If employee found then we remove this employee by calling remove method of context, else we return 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 Core Code First Approach - YogeshHadiya.in


Step 2

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

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


Step 3

Now give an appropriate name and click on Add button. 

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

Constructor Of Controller

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

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

For this controller, we are using routing with action methods. For example if user called Employee with Get method then it will call Get List Of All Employee Method and if 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 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();
    }
}
C#

in above method we call method from our service and assign to variable. If variable 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();
    }
}
C#

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();
    }
}
C#

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();
    }
}
C#

 

Test API Using Swagger

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

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


Add New Employee

Expand Save Employee Method and click on try it now button. Now json fields are editable, to add data in 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 Core Code First Approach - YogeshHadiya.in


 

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


 

Update Existing Employee

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

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


 

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


Get Employee Details By Id

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


Get List of Employees

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


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


Delete Employee

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


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


If Employee Not Exist

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


 

Conclusion

In this article, we create 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 with your friends.