Building ASP.NET Web API In .NET Core With Entity Framework

Background

ASP.NET Web API is a framework that helps to build HTTP(s) services that connect to a wider range of clients, including browsers and mobile devices. ASP.NET Web API is an ideal platform for building RESTful applications. In this article, you will learn how to build a simple Web API with Read, Create, Update and Delete action with HTTP verbs of GET, POST, PUT and DELETE respectively and will test the Web APIs with the Postman tool.

Here will consider a simple and basic model as ‘Employee’ and will use an Entity Framework with SQL Server database.

Prerequisites

  • Visual studio 2019 or Visual Studio Code or Rider IDE
  • Postman Tool
  • SQL Server Management Studio 18
  • SQL Server 2019

Let me make this article easy to understand and help you explore in a more advanced way. Please put aside  20 minutes to go through this article.

Here will see most of the details with pictorial representation and some code snippets. That will be as easy to dive into and understand.

Note: The highlighted area with Red is very important.

Part A - Implementation of Entity Framework

Step 1 - Open the IDE

Here will use the IDE - Visual Studio and select the project type as “ASP.NET Core Web App”.

Step 2

Give the project name and click on Create, proceed with the type of Web Application.

Step 3

Choose the API option to create a default project with ASP.NET core RESTful HTTP services.

Step 4

Now, you should able to see the project as below. Will delete the default files highlighted in Red.

Step 5

Install following Nuget packages with NuGet package Manager and installed packages as below,

Here is the short description of each package as below,

Step 6

Create a Folder ‘Models’ in solution and Add a new class ‘Employee.cs’,

namespace WebApiCoreWithEF.Models
{
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;

    [Table("Employee")]
    public class Employee
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int EmployeeId { get; set; }

        public string EmployeeName { get; set; }

        public string DateOfBirth { get; set; }

        public string Gender { get; set; }

        public string CurrentAddress { get; set; }

        public string PermanentAddress { get; set; }

        public string City { get; set; }

        public string Nationality { get; set; }

        public string PINCode { get; set; }
    }
}

Step 7

Define the DB Context, create a Folder ‘Context’ in solution and Add a new class ‘CompanyContext.cs’.

namespace WebApiCoreWithEF.Context
{
    using Microsoft.EntityFrameworkCore;
    using WebApiCoreWithEF.Models;

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

        }

        public DbSet<Employee> Employees { get; set; }
    }
}

Step 8

Define the connection string in ‘appsettings.json’, the easy way to find the connection string. Go to ‘Server Explore’ -> ‘Connect to DB’.

8a. Select the Database Source: Microsoft SQL Server (SqlClient).

8b. To connect locally, give . (DOT) in Server name. Or mention the remote server name.

8c. Select any available DB as mentioned in the below snap and click on OK.

8d. Open ‘appsettings.json’ and define the connection string.

Step 9

Now, we will create a Database with Employee Entity by running the DB Migration commands in the Package manager console.

9a. Add DbContext in ConfigureServices of Startup.cs,


services.AddDbContext<CompanyContext>(options => options.UseSqlServer(Configuration.GetConnectionString("CompanyConnStr")));

9b. Rebuild the solution.

9c. Open the Package manager console and run the following command to create a migration of CompanyContext.

PM> add-migration MigrationV1

9d. Once MigrationV1 is run successfully, you will find the following migration files are generated automatically in the solution.

9e. Here, generated migration will have the schema of the Table.

9f. We can remove the created migration by running the below command in the Package Manager console. This step is optional.

PM> remove-migration

9g. Now, these migration files need to be executed to update the physical Database. Run the following command in the Package Manager console.

PM> update-database

9h. Open SQL Server Management Studio and should able to create a Database schema of ‘CompanyDB’.

Step 10

Let’s create a Seed DB with few employee records. This is optional if you can create seed data via SSMS(SQL Server Management Studio).

namespace WebApiCoreWithEF
{
    using System.Linq;
    using WebApiCoreWithEF.Context;
    using WebApiCoreWithEF.Models;

    public static class InitialData
    {
        public static void Seed(this CompanyContext dbContext)
        {
            if (!dbContext.Employees.Any())
            {
                dbContext.Employees.Add(new Employee
                {
                    EmployeeName = "Employee001",
                    Gender = "Male",
                    DateOfBirth = "01-01-1990",
                    Nationality = "Indian",
                    City = "Bangalore",
                    CurrentAddress = "Current Address",
                    PermanentAddress = "Permanent Address",
                    PINCode = "560078"
                });
                dbContext.Employees.Add(new Employee
                {
                    EmployeeName = "Employee002",
                    Gender = "Female",
                    DateOfBirth = "01-01-1994",
                    Nationality = "Indian",
                    City = "Bangalore",
                    CurrentAddress = "Current Address",
                    PermanentAddress = "Permanent Address",
                    PINCode = "560078"
                });
                dbContext.Employees.Add(new Employee
                {
                    EmployeeName = "Employee003",
                    Gender = "Female",
                    DateOfBirth = "01-01-1995",
                    Nationality = "Indian",
                    City = "Bangalore",
                    CurrentAddress = "Current Address",
                    PermanentAddress = "Permanent Address",
                    PINCode = "560078"
                });

                dbContext.SaveChanges();
            }
        }
    }
}

Step 11

Define the parameter at the ‘Configure()’ function call in Startup.cs. This step is optional if you skip step #10 of Part A. FYI: Here CompanyContext has been initialized at step #9a of Part A.

Step 12

Now, we will run the application on the Kestrel server. Rebuild the solution and hit on Run button with the following option selection.

Kestrel server console will be shown below. Application URL is defined in “launchsettings.json”.

While launching an application, seed DB is created as below,

Cheers!... 🍻We have implemented Entity Framework and working well with basic needs. We are 60% completed and now need to implement Web API to consume the Entity calls and perform CRUD operation in Part B.

Part B – Implementation of Web API

Step 1

Add an API Controller. Choose the Read/Write option, this will ease the development task with a default template.

Step 2

Implement the controller for each action to perform. The implementation is very simple as like a LINQ statement. For any WRITE operation with DB, SaveChanges() shall be called.

namespace WebApiCoreWithEF.Controllers
{
    using Microsoft.AspNetCore.Mvc;
    using System.Collections.Generic;
    using System.Linq;
    using WebApiCoreWithEF.Context;
    using WebApiCoreWithEF.Models;

    [Route("api/[controller]")]
    [ApiController]
    public class EmployeeController : ControllerBase
    {
        private CompanyContext _companyContext;

        public EmployeeController(CompanyContext companyContext)
        {
            _companyContext = companyContext;
        }

        // GET: api/<EmployeeController>
        [HttpGet]
        public IEnumerable<Employee> Get()
        {
            return _companyContext.Employees;
        }

        // GET api/<EmployeeController>/5
        [HttpGet("{id}")]
        public Employee Get(int id)
        {
            return _companyContext.Employees.FirstOrDefault(s => s.EmployeeId == id);
        }

        // POST api/<EmployeeController>
        [HttpPost]
        public void Post([FromBody] Employee value)
        {
            _companyContext.Employees.Add(value);
            _companyContext.SaveChanges();
        }

        // PUT api/<EmployeeController>/5
        [HttpPut("{id}")]
        public void Put(int id, [FromBody] Employee value)
        {
            var employee = _companyContext.Employees.FirstOrDefault(s => s.EmployeeId == id);
            if (employee != null)
            {
                _companyContext.Entry<Employee>(employee).CurrentValues.SetValues(value);
                _companyContext.SaveChanges();
            }
        }

        // DELETE api/<EmployeeController>/5
        [HttpDelete("{id}")]
        public void Delete(int id)
        {
            var student = _companyContext.Employees.FirstOrDefault(s => s.EmployeeId == id);
            if (student != null)
            {
                _companyContext.Employees.Remove(student);
                _companyContext.SaveChanges();
            }
        }
    }
}

Step 3

Update the launch URL with controller name in “launchsettings.json”.

Step 4

Rebuild the solution and hit on Run button. Now the Web APIs are up and running. Will test all the API using Postman tool and will be elaborated in Part C.

Part C – API Testing with POSTMAN Tool

Step 1

Open the Postman Tool. Seems our Web API is running at port 5001 with HTTPS protocol.

Step 2

Here API call URL will be https://localhost:5001/api/Employee

Step 3  GET Operation

3a. Let’s perform the GET action to retrieve all employee records.

Step 4  POST Operation

4a. Let’s perform POST action to add a new employee record.

4b. Verify the new employee record added. Employee004 has been added and able to see in GET request.

Step 5  PUT Operation

5a. Let’s perform PUT action to update one of the existing employee records. Pincode has been updated from 560078 - 560001.

5b. Verify the update of employee004 record. Employee004 has been updated pinCode from 560078 - 560001.

Step 6  DELETE Operation

6a. Let’s perform DELETE action to remove one of the existing employee records. Removes Employee004 record.

6b. Verify the employee004 record is deleted.

Summary

We have explored creating an Entity Framework project with step-by-step representation in Part A, then we have explored creating a Web API to perform the CRUD operation with Entity Framework in Part B, then we have used a POSTMAN tool as a client to test all the web APIs and observed the results in Part C. This approach of explanation that gives you to build an End-to-End project with ASP.NET Web API using Entity Framework.

I hope this article helps you to understand in a detailed way with step-by-step pictorial representation and it will be very easy to remember the implementation. Attached is the sample code for your reference. Thanks for reading the article.


Similar Articles