Entity Framework Core Console Application

In this step by step tutorial, you will learn how to build the Entity Framework core console application. We will show you how to create the console application and install the required dependencies. Then, we will create an entity model. We will create DBContext, which is used to manage the entity model by creating a DBSet Property.  Next, we will use the migration features of the Entity Framework Core (EF Core) to create the database. Finally, we will show you how to perform simple tasks like insert, query, update & delete operations on the model and persist the data into the database.

Install Visual Studio 2019

The code in this requires you to install Visual Studio 2019. You can head over to the How to download & Install Visual Studio 2019

Creating the Entity framework core Console Application

The first step is to create the EF Core console application.

Open Visual Studio 2019. Click on the Create a new project option. ( If Visual Studio is already open, then Select File -> New -> Project to open the New Project form)

Create new project in Visual Studio 2019

In the Create a new project wizard, select the Console option, and select the Console App (.NET Core) template. Click on Next when done

Create a new net core Console App project

In the Configure your new project wizard, enter the project name and click on Create to Create new Console Project.

Configure your new project wizard

Installing EF Core

Now, we need to install Entity Framework Core.

The Microsoft.EntityFrameworkCore is the core library. But installing that alone is not sufficient. We also need to install the EF Core database provider(s). There are many different database Providers currently available with the EF Core. You can find the complete list of database providers.

For Example, to use the SQL Server, we need to install the Microsoft.EntityFrameworkCore.SqlServer. For SQLite install the Microsoft.EntityFrameworkCore.Sqlite. When we install the database provider(s), they automatically install the Microsoft.EntityFrameworkCore.

For this tutorial, we will be using the SQL Server, Hence we will install the install the Microsoft.EntityFrameworkCore.SqlServer package.

We will use the NuGet Package Manager to install the Entity Framework core. 

Using the NuGet Package Manager to Install Entity Framework Core
  1. Click on Tools -> NuGet Package Manager -> Manage NuGet Packages for Solution.
  2. Click on Browse.
  3. Enter Microsoft.EntityFrameworkCore.SqlServer and hit enter to search.
  4. Select Microsoft.EntityFrameworkCore.SqlServer and on the right-hand side select the project EFCore.
  5. Click on Install.
  6. Click on I Accept, when asked.
  7. The Package Installs.
Installing Entity Framework Core Via NuGet Package Manager

Installing Entity Framework Core Tools

The Entity Framework Core Tools contains command-line interface tools (CLI). These tools contain the command to create migrations, apply migrations, generate script migrations, and generate code for a model based on an existing database.

Open the Manage NuGet Packages for Solution window again and search for the Microsoft.EntityFrameworkCore.Tools and install it.

Modeling the database

EF Core performs data access using a model. A model is nothing but a POCO class. In EF Core we call them entity class.

The EF Core maps these entity classes to a table in the database.

Now, let us create a Product entity class

  1. Right-click on the solutions folder and create the folder Models
  2. Under the Models folder right click and create the class Product
  3. Change the class to the public and add two properties id & name as shown below

The DBContext class

The DBContext class manages the entity classes or models. It is the heart of the Entity Framework Core. This class is responsible for

  1. Connecting to the database
  2. Querying & Updating the database
  3. Hold the Information needed to configure the database etc.

We create our own Context class by inheriting from the DBContext.

Under the model folder, create the EFContext class and copy the following code.

Now, let us understand each line of code.

Our EFContext class inherits from the DBContext class

Next, we have define our connection string.

The OnConfiguring method allows us the configure the DBContext. EF Core calls this method when it instantiates the context for the first time. This is where we configure the Context class. For Example, we configure the database providers, the connection string to use, etc.

The OnConfiguring method gets the instance of the DbContextOptionsBuilder as its argument. The DbContextOptionsBuilder provides API to configure the DBContext.

Inside the OnConfiguring method, we call the UseSQLServer extension method provided by the Microsoft.EntityFrameworkCore.SqlServer. The UseSqlServer method sets SQL Server as our database provider.  The first argument to the UseSqlServer method is the connection string to use.

We have hard coded connectionString in this example. But you can use the Configuration system provided by the .NET Core to store the connection string in external file.

DbSet

Creating the Model (Entity Type) is not sufficient to map it to the database. We must create a DbSet property for each Model in the context class. EF Core includes only those types, which have a DbSet property in the model.

The DBSet Provides methods like Add, Attach, remove, etc on the Entity Types. The Context class maps these operations into a SQL query and runs it against the database using the Database Providers.

Creating the database

Now, our model is ready. The model has one entity type Product. We have created EFContext class to manage the Model. We have defined the DbSet Property of the Product so that it is included in the Model. Now it is time to create the database.

In Entity Framework Core, we use Migrations to create the database.

Adding Migration

Click on Tools – > NuGet Package Manager > Package Manager Console to open the Console

Nuget Package Manager Console

Run the Add-Migration to create the migration.

EF Core Add-Migration

The Add-Migration generates the instructions to generate the SQL commands to update the underlying database to match the model. You can see that the three files are created and added under the Migrations folder.

Create the database

The next step is to create the database using the Migrations from the previous step.

Open the Package Manager Console and run the command Update-Database.

The update-database uses the migrations to generate the SQL Queries to update the database. If the database does not exist it will create it. It uses the connection string provided while configuring the DBContext to connect to the database.

update-database to create the database in EF Core Application

The Database

  1. Click on View -> SQL Server Object Explorer to Open SQL Server Object Explorer.
  2. Goto the (localDB)\mssqllocaldb
  3. You will see the EFCore database is generated as shown in the image below
EF Core Update-database

CRUD Operations

Let us now add simple create/read/update & delete operations on the Product Entity model and persist the data to the database.

Inserting Data

Inserting to the database is handled by the SaveChanges method of the DBContext object.  To do that, you need to follow these steps.

Create a new instance of the DbContext class.

Create a new instance of the domain class Product and assign values to its properties.

Next, add it to the DbContext class so that Context becomes aware of the entity.

Finally, call the saveChanges method of the DBContext to persist the changes to the database.

Here is the list of the complete insertProduct method, which is invoked from the Main method of the program.cs.

Run the code and Open the database to verify that the values are inserted.

Data Inserted in Entity Framework Core Application

Querying the Data

The queries are written against the Dbset property of the entity.  The queries are written using the LINQ to Entities API. There are two ways in which you can write queries in LINQ. One is method syntax & the other one is Query Syntax.

The following example code retrieves the Product using the Method Syntax. It uses the ToList() method of the DbSet. The ToList() sends the select query to the database and retrieves and convert the result into a List of Products as shown below. 

And in the Main method call the readProduct to see the list of Products.

Update the Record

The following code shows how to update a single entity.

First, we use the find method to retrieve the single Product. The find method takes the id (primary key) of the product as the argument and retrieves the product from the database and maps it into the Product entity.

Next, we update the Product entity.

Finally, we call SaveChanges to update the database

In the Main method invoke the updateProduct and then readProduct to verify whether the values are changed.

Delete the Record

The following code demonstrates how to delete the record from the database.

Deleting is done using the Remove method of the DbSet. We need to pass the entity to delete as the argument to the remove method as shown below

And in the Main method call the readProduct to verify whether the values are changed.

Summary

In this tutorial, we learned how to create a console project using Entity Framework core. We created a model. Added DBContext to the project and passed our connection string to it. Then, we added DbSet Property of the Product model to the Context class. The Context manages all models, which exposes the DbSet Property. Then, we used Migrations to create the database. Finally, we learned how to add/update & insert records into the database.

Reference

  1. Getting Started with EF Core
  2. Complete list of database providers.

5 thoughts on “Entity Framework Core Console Application”

Leave a Comment

Your email address will not be published.

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

Scroll to Top