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 the entity model. We will create DBContext, which is used to manage the entity model by creating a DBSet Property.  Next, we will use the migrations 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 2017

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

Creating the Entity framework core Console Application

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

  1. Open Visual Studio 2017.
  2. Click on File -> New -> Project to open the New Project form
  3. Select Visual C# -> .NET Core -> Console App (.NET Core)
  4. Name the App as EFCore
  5. Click OK to create the Application
Creating the Entity Framework Core Console Application

Adding EF Core libraries

The Microsoft.EntityFramework.Core assembly contains the core of the Entity Framework Core. But to work with EF Core, we also need to install the database provider. There are many different database Providers currently available with the EF Core. You can find the complete list of database providers.

Since we are using the SQL Server, we will install the Microsoft.EntityFrameworkCore.SqlServer package.

Since Microsoft.EntityFrameworkCore.SqlServer is dependent on Microsft.EntityFramework.Core installing it automatically installs the EF Core.

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 the Microsoft.EntityFrameworkCore.SqlServer and on 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

There are two more packages, which we need to install. 

  1. Microsoft.EntityFrameworkcore.SqlServer.Design
  2. Microsoft.EntityFrameworkcore.Tools

The above packages are required in the development phase of the application. They are used inside the Visual Studio NuGet Package manager console. They contain command like Add-Migration, Update-Database and Reverse engineer Scaffold-DbContext etc.

Creating the Entity Class

The Entity classes represent the Domain Model of the application. The EF Core builds the database based on the Entity Classes.

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.cs
  3. Change the class to the public and add two properties id & name as shown below

The DBContext class

The entity classes are managed by the DBContext API. The DBContext 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 DBContext 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 defined our connection string.

The OnConfiguring method allows us the configure the DBContext. An instance of the DbContextOptionsBuilder is passed as the argument to the OnConfiguring method. 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.  It takes the connection string as its argument.

optionsBuilder.UseSqlServer(connectionString);

Finally, we use the DbSet property for the entity class Product.

A DbSet represents an entity set. An entity set is defined as a set of entities of the same entity type. From the perspective of the database, it usually represents the table. Each Entity type must expose the DbSet Property to be able to participate in the CRUD Operations. DBSet Provides methods like Add, Attach, remove etc on the Entity Types.

Creating the database

So far we have created the product entity class. And created the DBContext to Manage database and added DbSet Property for Product entity class. 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 Add-Migration “NewDatabase” 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.

Creating the database

The next step is to create the database using the Migrations created in the last 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

Browsing 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 above
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 converts the result into List of Products as shown below. 

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

Read More: Querying in LINQ Entities in Entity Framework Core 

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 with entity framework core. We learnt how to create the model. We Created DBContext class and passed our connection string. We created DbSet Property of the Product model so as the model is managed by the DbContext. We then used the migrations to create the database. We later looked at how to add/update & insert records into the database using the DbContext.

3 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