How To Create Web API In ASP.NET Core MVC Using Entity Framework Core

In this article, we are going to deep dive into ASP.NET Core Web API to learn how to perform CRUD operation (Create, Read, Update, and Delete) using Entity Framework Core.

If you already know ASP.NET Web API, then you know about 70 percent. Now, you need to understand how to configure and use it with ASP.NET Core.

Along with this, you are also going to learn how to configure Entity Framework Core and POSTMAN app..NET Core

If you are new to.NET Core, read these articles to kick start your .NET Core knowledge.

Steps

  1. Database part
  2. Creating application
  3. Installing Package for Entity Framework Core from NuGet
  4. Adding Connection string and Setting up DbContext
  5. Adding CustomerTB Model in Models Folder
  6. Adding DbSet for CustomerTB Model in DatabaseContext class
  7. Adding packages to access to the scaffolding Template in ASP.Net Core MVC
  8. Adding Controller [CustomerController]
  9. Installing POSTMAN app in chrome for sending HTTP request and testing API
  10. Adding New Customer Detail
  11. Updating Customer Detail by Customer ID
  12. Get Customer Detail by Customer ID
  13. Get All Customer Details
  14. Deleting Customer Detail by Customer ID
  15. Completed

Step 1 Database part

Create a sample database with the name “CustomerDB” for showing the demo.

.NET Core

Inside this database, I have added CustomerTB table. You can see the structure of the table, below.

.NET Core

Step 2 Creating application

Now, let’s create.NET Core Web application.  Open Visual Studio IDE from Start page and click on "New Project" link.

.NET Core

It will open a new dialog with the name “New Project”. Inside that, from left pane, choose Templates >> Visual C# >> .NET Core Template. Then, in the middle pane, you will see .NET Core project template. Select "ASP.NET Core Web Application (.NET Core)”.

.NET Core

Next, we are going to name the project as “MVCCore3” and finally click on "OK" button to create a project. But, it will popup another dialog with the name “New ASP.NET Core Web Application (.Net Core)”.

.NET Core

Inside this dialog, choose “Web API” project template for creating a “Web API application” and click on the "OK" button.

Below is the complete project view of newly created project.

.NET Core

After creating the application, add references needed for Entity Framework Core.

Step 3 Installing Package for Entity Framework Core from NuGet

To install the package, just right click on the project (MVCCore3) and then, select "Manage NuGet package". The below dialog of Nuget Package Manager will pop up. In the browse tab, there is search box. Type “Microsoft.EntityFrameworkCore.SqlServer” and just click on "Install" button to install.

  1. Microsoft.EntityFrameworkCore.SqlServer

.NET Core

Step 4 Adding connection string and setting up DbContext

After adding reference, the next step is to add a connection string in appsetting.json file.

.NET Core

After adding a connection string, add a Class which will inherit DbContext class. But before doing this, let's start with creating a folder for Models and inside that, we are going to add this class.

For adding a folder, just right click on the project (MVCCore3) and choose "Add" from the menu that pops up and inside that, choose "New Folder".

Add - New Folder.

.NET Core

Now, let’s add a class with the name DatabaseContext in Models folder.

For adding model, just right click on Models folder and select Add >> Class. The "Add New Item" dialog will pop up with default class selected. Name the class as DatabaseContext and click on "Add" button.

.NET Core

After adding a DatabaseContext class, next we are going to inherit DbContext class.

After inheriting with DbContext, next we are having created a constructor which takes DbContextOptions as an input parameter and inherits a base class constructor ( base(options)) [DbContext].

.NET Core

Next, add new Service in Startup.cs class for injecting dependency.

Now, whenever you use DatabaseContext class, the DbContext instance will be injected.

.NET Core

After completing with add service, next we are going to add Model.

Step 5 Adding CustomerTB Model in Models Folder

For adding model, just right click on Models folder and select Add >> Class. In the "Add New Item" dialog, name the class as CustomerTB and click on "Add" button.

Adding Model CustomerTB

.NET Core

Step 6 Adding DbSet for CustomerTB Model in DatabaseContext class

Now, let's add DbSet for CustomerTB Model in DatabaseContext class, as shown below.

.NET Core

Note  By default, ASP.Net Core MVC does not provide scaffolding template.

Step 7

Adding packages to access to the scaffolding template in ASP.NET Core MVC.

.NET Core

Code snippet to add in dependencies section

Add these 2 packages under dependencies section.
  1. "Microsoft.VisualStudio.Web.CodeGeneration.Tools" {  
  2.     "version"  
  3.     "1.0.0-preview2-final""type"  
  4.     "build"  
  5. }, "Microsoft.VisualStudio.Web.CodeGenerators.Mvc" {  
  6.     "version"  
  7.     "1.0.0-preview2-final""type"  
  8.     "build"  
  9. }  
Now, after adding 2 packages in dependencies section, next we are going to add "Microsoft.VisualStudio.Web.CodeGeneration.Tools” package in “tools” section, as show below.

Code snippet to add in Tools section
  1. "Microsoft.VisualStudio.Web.CodeGeneration.Tools" {  
  2.     "version"  
  3.     "1.0.0-preview2-final""imports" ["portable-net45+win8"]  
  4. }  
.NET Core

Now, after adding packages, just save it and build the project.

.NET Core

Step 8 Adding Controller [CustomerController]

For adding Controller, just right click on Controller folder and select Add >> Controller.

.NET Core

After selecting Controller, a new dialog will pop up with the name "Add Scaffold".

.NET Core

In this dialog, choose “API Controller with actions, using Entity Framework Template” and click on "Add" button. A new dialog will pop up with the name "Add Controller", as shown in below snapshot.

Next, add the Controller from scaffold mechanism. We need to provide specific inputs to it.
  1. Model that we are going to use [Model class CustomerTB]
  2. Data context class which we have created [DatabaseContext]
  3. Controller name which we want.

    .NET Core

After providing all inputs to "Add Controller" dialog, just click on "Add" button. It will generate the complete code with basic CRUD operation for API.

.NET Core

After adding CustomerController, let’s look at the complete code of Action Methods one by one.

Constructor which takes DatabaseContext as input parameter

.NET Core

GetCustomerTB Action Method will get all customers details from database

No parameter is needed to be passed

.NET Core

GetCustomerTB by CustomerID Action Method will get customer detail from database according to CustomerID we provide

Parameter to pass

  1. Need to pass CustomerID

    GetCustomerTB by CustomerID Action Method will get customer detail from database according to CustomerID we provide

PostCustomerTB Action Method will create new customer

Parameter to pass

  1. Need to pass CustomerTB object [Json format]


PUTCustomerTB Action Method will update customer details in database

Parameter to pass

  1. Need to pass CustomerTB object [Json format] along with CustomerID

    PUTCustomerTB

DeleteCustomerTB Action Method will delete customer detail from database according to CustomerID we provide

Parameter to pass

  1. Need to pass CustomerID

    PUTCustomerTB

After having looked at each action method in detail, next we are going to save this application and run it to send the HTTP request. But, before that, we need some tools to send Http Request and for doing that, we are going to install Postman REST client in Chrome browser.

Step 9 Installing POSTMAN app in Chrome for sending HTTP request and testing API

For downloading POSTMAN APP, just copy and paste the URL into the browser https//www.getpostman.com/

PUTCustomerTB

You will find 3 buttons to download. You can download any one version according to your Operating System. For this demo, I am going to use Chrome app. After clicking on Chrome button, it will open another page, as shown below, with add extension button.

Note You see the "Launch App" button because I have already installed it.

PUTCustomerTB

Now, after installing POSTMAN APP in Chrome browser, just type “chrome//apps/” to see the installed apps, as shown below.

PUTCustomerTB

Now, just click on “Postman”. It will take awhile to load. Given below is the completed UI of Postman app.

PUTCustomerTB

After installing Postman app, just save and run the application.

Step 10 Adding new Customer Detail

In this part, we are going to add new Customer by sending HTTP POST request using “Postman” app.

Before sending request, we need a URI for sending a request. For getting that to run in the application, we are going to get Port number.

PUTCustomerTB

URI for Post request - http//localhost6899/api/Customer

PUTCustomerTB

Steps to send request

  1. Add URI
  2. We are going to send data from body so choose body tab in Postman app
  3. The data we are sending is in Json format that why we have chosen [Json(application/json) header]
  4. Then finally click on Send button to send the request.

Below is debug view after sending POST request

PUTCustomerTB

After sending request, we are also getting a response in return, as show below.

PUTCustomerTB

Response

In response, you will get customer details along with Status Code - 201(Created). After getting a response, now, let's have a look if the database has been inserted in CustomerTB table.

CustomerTB table view after sending post request

PUTCustomerTB

After completing adding new customer details, let’s try to update customer details.

Step 11 Updating Customer Detail by Customer ID

In this part, we are going to update Customer by sending HTTP PUT request using “Postman” app

We are just going to update the name from ‘Sai’ to ‘Saineshwar Bageri’.

URI for PUT request - http//localhost6899/api/Customer/1

Note

Now, we are updating that data, that's why we need to send CustomerID which we have already inserted.

PUTCustomerTB

Response

In response, you will only get Status Code - 204 (the Server successfully processed the request but it is not returning any content).

Steps to send request

  1. Add URI. Along with that, we need to pass CustomerID in URI [http//localhost6899/api/Customer/1]
  2. We are going to send data from body that is why we choose body tab in Postman app
  3. The data we are sending is in JSON format that is why we have chosen [Json(application/json) header]
  4. Then finally, click on "Send" button to send the request.

Below is the debug View after sending PUT request.

PUTCustomerTB

CustomerTB table View after sending PUT request.

PUTCustomerTB

After completing with updating customer details, now, let’s get customer data by CustomerID

Step 12 Get Customer Detail by Customer ID

In this part, we are going to get customer details by sending HTTP GET request using “Postman” app.

Here, we need to send CustomerID for getting Customer Details; as you can see, we have appended CustomerID at last in URI.

URI for GET request - http//localhost6899/api/Customer/1

PUTCustomerTB

Response

In response, you will get customer details for CustomerID you have passed, along with the Status Code - 200 (OK)

Below is the debug View after sending GET request

PUTCustomerTB

After completing getting customer details by CustomerID, now let’s get all customer details.

Step 13 Get All Customer Details

In this part, we are going to All Get Customer Details by sending HTTP GET request using “Postman” APP.
URI for GET request - http//localhost6899/api/Customer

Here we are going to get all Customer Details hence we do not need to pass any parameter or header.

PUTCustomerTB

Response

In Response, you will get all customer details along with Status Code - 200 (OK)

Below is debug view after sending GET request

PUTCustomerTB

After completing getting All Customer Details now let’s try to delete Customer Detail by CustomerID.

Step 14 Deleting Customer Details by Customer ID

In this part, we are going to Delete Customer by sending HTTP DELETE request using “Postman” APP.

URI for Delete request - http//localhost6899/api/Customer/1

Here, we need to send CustomerID for Deleting Customer Details; as you can see, we have appended CustomerID at last in URI.

PUTCustomerTB

Response

In response, you will get deleted customer details for CustomerID you have passed, along with the Status Code - 200 (OK).

Below is debug view after sending Delete request

PUTCustomerTB

CustomerTB table view after sending Delete request

PUTCustomerTB

Finally, we have learned how to create Web API in ASP.Net Core MVC using Entity Framework Core.

I hope you liked my article. Please share it.