In this article, we are going to get started with EF Core in ASP.NET Core. We are going to show you how to create model classes and how to create and prepare a context class. Additionally, we are going to talk about the DbContext class in detail and show you how it helps with the database modeling process.

Overall we are going to go through a variety of basic but crucial information that will be valuable to you when starting with an ASP.NET Core project that uses EF Core as ORM (object relational mapper).

You can download the source code for this article on our GitHub repository.

We strongly recommend you visit the main page for this tutorial which contains all the basic instructions and complete navigation.

Entities (Models) – The Classes That Map to the Database

Before we start talking about model classes, we need to create an ASP.NET Core project for the model classes to reside in. So, we are going to create an ASP.NET Core Web API project by using ASP.NET Core version 3.1:

Creating ASP.NET Core App - EF Core

We have to install Microsoft.EntityFrameworkCore and Microsoft.EntityFrameworkCore.SqlServer libraries. You can do that by using the NuGet Manager or with the Package Manager Console window.

The model (entity) class is a class that Entity Framework Core uses for mapping to the database table. So, let’s create our first entity and then explain how EF Core creates a table from the created class.

Let’s create a folder Entities and inside a class named Student:

public class Student
    public Guid StudentId { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }

There are a couple of rules that help EF Core to map this class to the database table and we are going to explain the whole process.

First of all, by using the name of our class, EF Core has the information which table to use for the columns and configuration mappings (as soon as we create the context class it will become much easier to understand how EF Core knows that).

Next, all the public properties from this class are going to be mapped to the table’s columns with the same names. Finally, EF Core uses a naming convention to create a primary key, from the StudentId property, in the database table (Later on, in the Configuring Nonerelational Properties section, we are going to see how).

Providing the ConnectionString for EF Core in ASP.NET Core

Creating a model class or model classes is just one part of a puzzle. In order for EF Core to have the required information about the database to work with, we need to provide a connection string by modifying the appsettings.json file.

Placing a connection string into the appsettings.json file is a common practice (and we are going to use the same practice in this article) because we can use different appsettings files for different environments:

  • Development.json – Holds the settings related to a development environment
  • Production.json – Holds the settings related to a production environment
  • appsettings.json –  Holds the settings that are common to both environments

But, we must state that using appsettings files to store connection string (or other sensitive data) isn’t the best practice, especially for the production environment. In such a case, the better way is to use environment variables.

Because we are not going to publish our app to the production environment, we are going to modify the appsettings.json file:

  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
  "ConnectionStrings": {
    "sqlConnection": "server=.; database=CodeMaze; Integrated Security=true" 
  "AllowedHosts": "*"

As you can see, we are providing the database server name, the name of the database itself and the authorization information. Of course, you need to provide a valid name for the server part.

That is it, we can continue towards the context class.

DbContext Class and its registration in ASP.NET Core

The context class is another important part of the application. This class must inherit from the DbContext base class which contains information and configuration for accessing the database. So, let’s create our context class named ApplicationContext in the Entities folder:

public class ApplicationContext : DbContext
    public ApplicationContext(DbContextOptions options)

    public DbSet<Student> Students { get; set; }

Additional options are sent to the base DbContext class through the ApplicationContext constructor by using DbContextOptions parameter. Finally, we see the Students property of type DbSet<Student> and this is quite an important part.

EF Core looks for all the public DbSet properties, inside the application’s context class, and then maps their names to the names of the tables in the database. Then it goes inside a class which is provided in the DbSet<T> property (in our case it is a Student class) and maps all the public properties to the table columns in the table with the same names and types (StudentId, Name, and Age).

If our Student class has any references towards other classes (right now it doesn’t but we will create relationships in the following articles), EF Core would use those reference properties and create relationships in the database.

Registering a Context Class in the ASP.NET Core’s IOC

After we have finished with creating the ApplicationContext class, we can proceed towards its registration.

To do that, we are going to open the Startup.cs class and modify the ConfigureServices method:

public void ConfigureServices(IServiceCollection services)
    services.AddDbContext<ApplicationContext>(opts =>


We are using the AddDbContext extension method to register our ApplicationContext class into the IOC container. Inside the UseSqlSrver method we are providing the connection string to our context class and we can provide additional options as well (when it comes to that).

About AddDbContextPool

Instead of the AddDbContext method, we can use the AddDbContextPool method. We can use either the first or the second method, but with the second method, we enable DbContext pooling. This will not create a new instance every time but will check first if there are available instances in the pool and if there are, it will use one of those.

Right now our context class is ready to be used with the Dependency Injection (DI) inside our application. So let’s add the Values (API empty) controller and modify it:

public class ValuesController : ControllerBase
    private readonly ApplicationContext _context;

    public ValuesController(ApplicationContext context)
        _context = context;

    public IActionResult Get()
        //Logic with the injected _context object.

We can see that we are injecting our context class inside the controller’s constructor, which is the usual way for DI.

To learn more about DI and IOC, and service lifetime overall, you can read the Configuring Services in ASP.NET Core part of our article.

Diving Deeper into the DbContext Class

Our ApplicationContext class currently accepts one parameter of type DbContextOptions inside a constructor. But we can provide the generic version of the DbContextOptions parameter as well:

public ApplicationContext(DbContextOptions<ApplicationContext> options)

Whether we use the generic or non-generic version of the DbContextOptions parameter, our application is going to work the same. The main difference is that the non-generic version is not recommended if our application has multiple context types, which is not the case right now.

If we navigate to the DbContext’s definition, we are going to see that it has three properties inside:

  • Database – This property is responsible for the Transactions, Database Migrations/Creations and Raw SQL queries (we are going to talk about all of these in the following articles)
  • ChangeTracker – This property is used to track states of the entities retrieved via the same context instance (this will be covered as well in the following articles)
  • Model – This property provides access to the database model that EF Core uses when connecting or creating a database.

We can use the Model property to access the information for each entity and its properties.

But before we do that, let’s install the required Microsoft.EntityFrameworkCore.Relational package.

After the installation, we can modify our Get action:

var entity = _context.Model

var tableName = entity.GetTableName();
var schemaName = entity.GetSchema();
var key = entity.FindPrimaryKey();
var properties = entity.GetProperties();

These are just a few examples of using the Model property, but still, we can see its purpose.


Excellent. We’ve successfully integrated Entity Framework Core inside our ASP.NET Core application and we can move on towards all the different features it provides us.

To sum up, we have learned:

  • What the entity (model) class in EF Core represents
  • How to provide connection string for our application
  • How to create the context class and why it is of such importance to us
  • Some additional information about the DbContext class

In the next article, we are going to talk about Configuring Nonrelational Properties in EF Core.