Back-End Development

.NET MVC Framework – Async Calling DbContext In a Controller Using a Provider Class

Typing on laptop

Hello all! In this last part of the tutorial series, I will be going over how we can query data from the database and pass it to the view by asynchronously calling DbContext in the controller.


1) Create a DTO (Data Transfer Object) in ’03 – Domain > Models’ folder.

public class CustomerDto {
    public int ID { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
  • A DTO is just like a Model where we define properties with getters and setters.
  • As the name implies, DTOs are used in lieu of actual Models to “transfer data” to the controller.

2) Create a Provider class which will act as an intermediary between the DbContext and the controller.

  • Where we will be creating an async method to call DbContext and store the data in the DTO.
  • This async method will be called in the controller where the data will then be passed to the view.

Where We are Going to Start From

In part 1 of this tutorial, I shared how you could construct the folder structure for ASP.NET MVC project integrating the database-first entity framework. In part 2, I explained how you could publish the database and reverse engineer to create Dbset models. This is the folder structure we are going to start from based on the previous tutorials (by no means you need this to follow along):

Bp4 P1

Creating a DTO and a Provider Class

1) Add a ‘CustomerDto’ class under ’03 – Domain > Models’ folder. Add the properties (fields) with getters and setters.

Bp4 P2

In this folder structure that I am working in, notice how the CustomerDto is stored in the Models folder under ’03 – Domain’, while the actual Customer Model is stored in the Models folder under ’04 – Database’.

Bp4 P3

**Before moving on, we need to override DbContext.OnConfiguring(DbContextOptionsBuilder) method in the DatabaseContext to configure the database to be used for this context.

  • This sets up the connection to the database using connection string configured in web.config. In other words, we need to add the connection string in the web.config too if we don’t have it!

Bp4 P4

Bp4 P5

Inside the connection string, data source is the name of the server (e.g. . or localhost), Initial Catalog is the name of the table we are interacting with, while Integrated Security=True allows us to access the database using Windows Authentication. There are resources online, including this one I found:

2) Now we can add a ‘CustomerProvider’ class under ’02 – Application > Providers’ folder.

  • Declare the DbContext
  • Create constructors (constructor chaining is used) that will instantiate the DbContext using Dependency Injection
Covid 19
COVID-19: Digital Insights For Enterprise Action

Access Perficient’s latest insights into how you can leverage digital technologies to not only respond to the pandemic, but drive your operations forward and deliver experiences your customers need.

Get Informed

Bp4 P6

3) Add a GetCustomersAsync() method that will store data from DbContext in a list of CustomerDto using LINQ.

  • Task<> represents a single operation that usually executes asynchronously.
  • In our example, we are using LINQ to .Select variable (Id, Name, & Email) to store each of them in the variables of CustomerDto object. We are using .SingleOrDefaultAsync() method to return the CustomerDto object.
  • .AsNoTracking() is conventionally used because entities returned will be cached in the DbContext by default, rendering errors when we are calling an entity in different places at the same time.

Bp4 P8

We can use .ToListAsync() method to return a list of objects as demonstrated below.

Bp4 P9

Along the way, you might have to install packages (Microsoft.EntityFrameworkCore) to add a reference to the DbSet.

Bp4 P7

NOTE: We will need to install couple of Nuget packages to use the Task class and SqlClient for DbContext to interact with the Sql Server. Without the installations, you might encounter errors like “Could not load file or assembly ‘System.Threading.Tasks.Extensions'” like the one shown below:

Bp4 P10

To install those Nuget packages, go to Package Manager Console.

Bp4 P11

Paste each of those lines at ‘PM >’

PM > Install-Package System.Threading.Tasks.Extensions -Version 4.5.4

PM > Install-Package Microsoft.Data.SqlClient -Version 2.1.0-preview1.20235.1

For updated versions at the time of your reading, click here for System.Threading.Tasks.Extensions and here for Microsoft.Data.SqlClient.

That is pretty much it for creating DTO and async method in the provider class. Now we can call the method from the controller and pass it to the view!

Creating a Controller and View

1) In our examples, we will be using IndexController. Create constructors to instantiate the providers. I can call .GetCustomerAsync() method that I created in the provider class and store it in a variable. We will then pass this variable to the view.

Bp4 P12

2) This is how our razor page and the view will look like!

Bp4 P13

Bp4 P14How our Demo_01 database looks like

Bp4 P15

Hope that helped!

About the Author

David Hwang is an Associate Technical Consultant in the Sitecore/Microsoft Business Unit. He will be blogging about various concepts in technologies for beginners.

More from this Author

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Subscribe to the Weekly Blog Digest:

Sign Up