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 which 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.

This post is divided into several parts:

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 2.2:

Creating ASP.NET Core App - EF Core

This newly created application contains all the required EF Core libraries and tools as a part of the Microsoft.AspNetCore.App (2.2.0) package. So, this means, we don’t have to install any additional libraries but instead to get right down to business.

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:

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:

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:

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:

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).

Right now our context class is ready to be used with the Dependency Injection (DI) inside our application:

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:

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:

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

Conclusion

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.

If you have enjoyed reading this article and if you would like to receive the notifications about the freshly published .NET Core content we encourage you to subscribe to our blog.