C sharp (C#)

Entity Framework Core: EF Core, Entity Framework C#

Entity Framework Core or EF Core C#, Overview:

Entity Framework Core “EF Core” C#- It’s safe to say that data is the most valuable aspect of a business application. Not surprisingly, a fairly large percentage of application code usually deals with storing and retrieving data. This includes reading data from the data store, tracking changes, and saving changes to the same data store. Over the years, several .NET technologies have emerged that make this task easier. There are not many solutions that give rise to such polar opinions as the choice of technology and methodology for storing and retrieving data in applications.

Entity Framework (EF) Core is the latest data technology created by the ASP.NET development team. This particular Entity framework is the recommended framework for building ASP.NET Core applications. Entity Framework Core or EF Core is classified as an Object Relational Mapper (ORM); this means you get rid of the complexities of transforming data from relational storage and your application’s object-oriented domain model. Entity Framework Core or EF Core isn’t the only ORM technology available for .NET Core applications. Dapper is a popular “micro ORM” framework and nHibernate is a fully featured ORM framework. Both frameworks are open source and community driven, but at the time of this writing, only Dapper has support for .NET Core. The main difference between a micro-ORM and a full-fledged ORM framework (such as the Entity Framework Core) is that a micro-ORM usually requires you to manually enter executable SQL commands, and ORMs generate most of the SQL commands for you based on the information about the entities and the base data. The choice between ORM and micro-ORM ultimately depends on the team and the tasks you are trying to solve.

The system was relatively lightweight and easier to expand compared to previous versions of Entity Framework EF. Another benefit was LINQ support, used to efficiently build model queries by expressing meaningful queries in C# code. Entity Framework Core or EF Core also provides a simple mechanism to use SQL when needed – for performance reasons or just for convenience.

Amazon Purchase Links:

Top Gaming Computers

Best Laptops

Best Graphic Cards

Portable Hard Drives

Best Keyboards

Best High Quality PC Mic

Computer Accessories

*Please Note: These are affiliate links. I may make a commission if you buy the components through these links. I would appreciate your support in this way!

Entity Framework Core Basics

When using the Entity Framework as a data layer, the domain model expression is performed through POCO objects (Plain Old CLR Objects). For example, the domain entity “map” can simply be expressed as the SkiCard class. Entity Framework takes care of all the hassle of mapping class properties to columns in a specific database table. The Entity Framework Core manages the display and any interactions with the database through an instance of the class that inherits from DbContext.

A very simple SQL Server database in which a list of all resorts is stored in the Resorts table (Table 1).

Table 1: Resorts table

Id Int
Name nvarchar(255)
OperatingSince date

The application models the Resort record with a POCO object named Resort. Such classes are called entity classes.

Next, you need to add a reference to the Microsoft.EntityFrameworkCore.SqlServer package, which retrieves all the required Entity Framework Core or EF Core components. But so far Entity Framework Core does not know anything about the essence of the Resort. To tell Entity Framework this information, create a DbContext class that contains a DbSet for Resorts.

That’s all it takes to get started using the Entity Framework. The Entity Framework Core conventions will ensure that the Resort class is mapped to the Resorts table in the database. All of these conventions can be overridden as needed, but first let’s look at the basic DbContext API, which provides a useful abstraction of the database. To access data in the database, start by creating an instance of ResortContext.

It is important to call the Dispose method after you are finished with the DbContext instance. Calling Dispose ensures that all database connections are returned to the connection pool. If connections are not returned to the pool, there is a risk of depleting the connection pool, eventually leading to timeouts. When manually creating a context, it is recommended that you use the using pattern to ensure that the Dispose method is called when the block of code is completed.

In an ASP.NET application, use the built-in dependency injection framework to create and destroy contexts.

Request to get one record:

To get one record by primary key, use the DbSet.Find method:

If the query to retrieve one record is based on criteria other than the primary key, use the First method and provide a lambda expression that returns true for the matching record:

Resulting Query:

If no match is found, the First method throws an exception. You can also use the FirstOrDefault method, which returns Null if no match is found.

Another possible solution is to use the Single and SingleOrDefault methods. These methods work in much the same way as the First and FirstOrDefault methods, but they will throw an exception if more than one matching record is found.

Resulting Query:

Note:  Entity Framework Core EF generates SELECT TOP (2) for Single – instead of SELECT TOP (1) as for First. The SELECT TOP (2) query is required so that if multiple records are found, the EF framework can throw an exception. Use Single if you expect to find only one matching entry, because this method more clearly expresses the meaning of the request and throws a well-defined error if expectations are not met.

Request to get multiple records:

In many cases, you need to query multiple records from the database that meet some criterion. The problem is solved by calling the Where method of the DbSet object; the method returns all records that match the given lambda expression.

Resulting Query:

Entity Framework Core or EF Core does not make a call to the database directly at the time of the call to Where. Instead, an IQueryable <T> object is returned, where T is the type of the requested entity. The actual execution of the query is deferred until a method is called for the IQueryable <T> requiring the query to be executed. In this case, calling the ToList method forces immediate execution. Deferred query execution is an important feature of Entity Framework EF that allows you to chain method calls and build complex queries. This is an example of a deferred execution pattern in which the creation of an object or the calculation of a value is deferred until it is first requested.

Saving data using entity framework core:

DbContext also provides a mechanism for tracking changes to entities and saving those changes to the database. Let’s look at the basics of saving changes.

Data insertion is implemented by adding a new entity to the DbSet and then calling the SaveChanges method of the DbContext object:

Resulting Query:

Several entities can be added to the DbSet before calling SaveChanges. Entity Framework keeps track of all new entities. When SaveChanges is called, EF sends insert commands to the database. At this point, a transaction is created, and all insert commands are executed in that transaction. If at least one insert command fails, then all commands are rolled back.

Tracking changes:

The DbContext change tracker also tracks changes in existing entities and issues Update commands when SaveChanges is called:

Only the [Name] column is updated. The other columns are not updated because the change tracker knows these columns have not changed. Tracking changes comes with certain additional costs. If entities are loaded read-only, it might be helpful to disable change tracking. This can be done on a case-by-case basis using the AsNoTracking () extension method.

Resulting Query:

Using migrations to create and update databases:

So far, our simple example has assumed that a database already exists in the system corresponding to our entities. Developers want a simple mechanism for creating a local test database. You also need to define and execute migration scripts when you make changes to the database. Entity Framework Core or EF Core provides a command line toolkit to automate these tasks. Command line instrumentation is enabled via NuGet by adding a dependency for the Microsoft.EntityFrameworkCore.Tools package and running the dotnet ef command.

Creating a new database:

The new database is created with the dotnet ef database update command:

The command compiles the application and connects to the database using the connection string specified in the local development environment configuration.

If the specified database does not exist, a new database is created. If the database exists, any migration scripts required to update the database to match the domain classes in the application are applied.

You can also explicitly set the name of the DbContext class to be used by the command.

The -c (or –context) parameter can be passed to any of the dotnet ef commands and is required if your application uses more than one DbContext class.

Adding migrations:

Entity Framework migrations are used to upgrade (upscale or downgrade) a database. Migration is defined as a C# class that inherits from the Migration class. The class contains two methods: Up() to upgrade the version defined by the migration, and Down () to roll back to the previous version.

Defining migrations manually would be extremely tedious, so the Entity Framework supports the dotnet ef migrations add command, which takes care of most of the routine. In the case of a new DbContext class, a new migration is needed to create your model tables.

dotnet ef migrations add CreateInitialSchema

This command creates a new class named CreateInitialSchema in the Migrations folder next to the specified DbContext class.

In this case, the Up method adds a Resorts table with a corresponding column for each property of the Resort class. The Down method drops the Resorts table. In the local development environment, CreateInitialSchema is considered a pending migration because it has not yet been applied to the local database.

dotnet ef database update

When you make changes to the domain class or when you add new classes, a new migration must be defined in the Migrations folder. A typical example of this kind is adding a new property to a domain class.

After adding a property, the domain model and the database are out of sync, and it is required to match the database with the model.


Start by running the dotnet ef migrations add command with a meaningful migration name.

> dotnet ef migrations add AddedMailingAddress

The Entity Framework compiles your application and finds any pending changes in the entity classes; a new class is added to the Migrations folder.

In this case, the Up method adds a new MailingAddress column, and the Down method removes the MailingAddress column. The dotnet ef database update command applies an unfinished migration.

The EF Migration Toolkit does a pretty good job of generating code to change the database structure, but sometimes you also need to make changes to the data with UPDATE, INSERT, or DELETE commands. Changes to data can be implemented by passing any syntactically correct SQL command to the migrationBuilder.Sql method in the Up or Down method. It is even possible to add migration without changing the model. The dotnet ef migrations add command without modifying the model results in an empty migration. Below is an example of a migration that simply adds rows to the Resorts table.


Engr Fahad

My name is Shahzada Fahad and I am an Electrical Engineer. I have been doing Job in UAE as a site engineer in an Electrical Construction Company. Currently, I am running my own YouTube channel "Electronic Clinic", and managing this Website. My Hobbies are * Watching Movies * Music * Martial Arts * Photography * Travelling * Make Sketches and so on...

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button