What is Entity Framework Core?

Entity Framework Core page

Entity Framework Core is a powerful cross-platform Object-Relational Mapping (ORM) tool developed by Microsoft for .NET developers.

It allows developers to interact with databases using .NET (C#) objects instead of writing SQL queries, thus making data access simpler and more flexible when building .NET applications.

This article will explore EF Core in depth and discuss how it can be used alongside third-party solutions.

Entity Framework Core architecture

The EF Core architecture is modular and designed to simplify data access and exchange between .NET applications and databases. Let us consider it thoroughly.

EF Core architecture

Application layer

The Application layer includes the business logic and UI/API code that uses EF Core to perform CRUD (Create, Read, Update, Delete) operations on the database. The .NET application resides in this layer and interacts with EF Core primarily through the DbContext class.

DbContext

The central component of EF Core functions as a bridge between the domain (entity classes) and the database. It represents the database session and provides an abstraction for querying and saving data. The key tasks it performs are:

  • Entity tracking - tracking changes to entities (objects) loaded from or attached to the context.
  • Query execution - translating LINQ queries into SQL and executing them against the database.
  • Database connection management - managing connections to underlying databases via a provider.
  • Configuration - customization of mappings, relationships, and behaviors through the OnModelCreating method or data annotations.

To define entity classes and their relationships, we must refer to DbContext and expose them as DbSet<TEntity> properties.

Entity classes (domain model)

Entity classes are plain C# classes (POCO - Plain Old CLR Objects) that represent the application's data structure. They map to database tables, and their properties map to table columns.

EF Core supports the following classes:

  • Conventions - default mapping rules (such as considering a property named Id as the primary key).
  • Data annotations - attributes like [Key], [Required], or [MaxLength], which are necessary to configure mappings.
  • Fluent API - a more flexible way to configure mappings in the OnModelCreating method of DbContext.

Model

The model in EF Core is an in-memory representation of the database schema, built from the entity classes and their configurations. EF Core creates and caches it with the first usage of DbContext. The model defines:

  • Entities (tables)
  • Relationships (foreign keys, one-to-many, and so on)
  • Property mappings (columns, data types, constraints)

Once built, the model can't undergo any changes, which ensures consistency in the application's work.

Change tracker

This internal component of DbContext monitors the state of entities (we’ll explore it further in this article). When we call SaveChanges(), EF Core uses the change tracker to determine what SQL commands (INSERT, UPDATE, DELETE) it needs to execute. The following tracking options are supported:

  • Snapshot tracking - the default mode in which EF Core keeps a snapshot of original values to detect changes.
  • Proxy tracking (optional) - suggests using dynamic proxies for more efficient change detection (requires specific setup).
  • No-tracking queries - for read-only scenarios where change tracking is disabled to improve performance.

Query pipeline

EF Core translates LINQ queries in C# into SQL queries that databases can understand. The query pipeline includes:

  • LINQ provider - it converts LINQ expressions into an abstract syntax tree.
  • Expression tree - it analyzes and optimizes the query.
  • Database provider - it translates the expression tree into database-specific SQL (for instance, SQL Server, MySQL, PostgreSQL)
  • Materialization - it converts the database results back into entity objects.

Data providers

EF Core uses a provider model to connect to different databases. Each provider is a solution that translates the commands from EF Core into database-specific SQL and handles communication. One of the popular examples of such data providers is the Devart dotConnect product line.

Database connection

The connection to the database is configured via a connection string. It is typically passed to the DbContext through the DbContextOptions object. EF Core supports:

  • Connection pooling - reusing connections for performance (handled by the provider).
  • Lazy loading - loading related data on-demand (optional, requires proxies or explicit configuration).
  • Explicit transactions - manual control over database transactions.

Dependency injection

EF Core is designed with dependency injection (DI), particularly in ASP.NET Core applications. DbContext is typically registered as a scoped service and can be injected into controllers or services. This improves modularity and testability.

Workflow overview

The EF Core workflow includes the following steps:

  • Defining entities - creating POCO classes and configuring them in DbContext.
  • Configuring DbContext - setting up the provider and connection string in DbContextOptions.
  • Querying data - using LINQ to query the database via DbSet.
  • Tracking changes - modifying entities and monitoring them with the change tracker.
  • Saving changes - calling SaveChanges() to persist changes to the database.

This architecture makes EF Core more flexible and suitable for modern .NET applications than the original Entity Framework.

Entity Framework or EF Core: version history

Microsoft introduced Entity Framework in 2008 with .NET Framework 3.5. Since then, it released several versions of Entity Framework. Currently, two versions are in operation: Entity Framework and Entity Framework Core (EF Core).

Entity Framework was released in 2008 alongside .NET Framework 3.5 SP1. It is a stable, feature-rich, open-source technology, but limited to Windows. Entity Framework supports .NET Framework 3.5 and later versions.

Entity Framework Core (EF Core) was introduced in 2016 with .NET Core 1.0. Like Entity Framework, it is open-source but offers cross-platform support, running on Windows, Linux, and macOS. EF Core is compatible with .NET Framework 4.5 and later, as well as .NET Core.

Below, you can see the history of the Entity Framework and EF Core versions.

Entity Framework version history

Entity Framework Version Release Year .NET Framework
Entity Framework 6 2013 .NET 4.0 & .NET 4.5, VS 2012
Entity Framework 5 2012 .NET 4.0, VS 2012
Entity Framework 4.3 2011 .NET 4.0, VS 2012
Entity Framework 4.0 2010 .NET 4.0, VS 2010
Entity Framework 1.0 (or 3.5) 2008 .NET 3.5 SP1, VS 2008

EF Core version history

EF Core Version Release Date Target Framework
EF Core 9.0 Nov 2024 .NET 9
EF Core 8.0 Nov 2023 .NET 8
EF Core 7.0 Nov 2022 .NET 6
EF Core 6.0 Nov 2021 .NET 6
EF Core 5.0 Nov 2020 .NET Standard 2.1
EF Core 3.0 Sept 2019 .NET Standard 2.1
EF Core 2.0 August 2017 .NET Standard 2.0
EF Core 1.0 June 2016 .NET Standard 2.1

Features of EF Core

Entity Framework Core is a multi-featured technology, so let us consider its key features and functionality.

Features Description
Cross-Platform Support EF Core is a cross-platform framework that runs on Windows, Linux, and macOS.
Querying EF Core provides powerful querying capabilities using LINQ (Language Integrated Query) in C# or VB.NET. The database provider translates LINQ queries into the appropriate database-specific query language (such as SQL for relational databases). EF Core also allows the execution of raw SQL queries directly on the database.
Change Tracking EF Core tracks changes made to entities and thus ensures database updates. It automatically generates the necessary SQL statements for Create, Read, Update, and Delete (CRUD) operations. EF Core also monitors changes in entity properties that need to be persisted in the database.
Saving Data EF Core executes INSERT, UPDATE, and DELETE commands based on entity changes when calling the SaveChanges() method. It also provides the asynchronous SaveChangesAsync() method for non-blocking operations.
Concurrency Handling EF Core uses Optimistic Concurrency by default to prevent data loss when multiple users modify the same data simultaneously.
Transaction Management EF Core automatically manages transactions when querying or saving data. It also provides options for custom transaction handling.
Caching EF Core includes first-level caching by default. Repeated queries return cached data instead of hitting the database.
Built-in Conventions EF Core follows the "convention over configuration" approach – it automatically applies default rules to configure the entity model.
Configurations Developers can customize the EF model using Data Annotations or the Fluent API to override default conventions.
Migrations EF Core provides migration commands that can be executed via the NuGet Package Manager Console or Command Line Interface (CLI). It ensures accurate schema change management over time and keeps database versioning aligned with the codebase.

Development approaches with Entity Framework

Entity Framework offers three main approaches for working with data models and databases: Database First, Model First, and Code First. Let's explore each method.

Database First Approach

You start by creating a database with all the necessary tables and elements. Entity Framework generates domain classes using the Scaffold-DbContext console command. This method is commonly used by developers who prioritize database design.

Database First Approach

Advantages

  • Quick setup for initial development
  • Works with existing databases
  • Preserves the original database schema

Disadvantages

  • Synchronizing changes between the database and model can be complex
  • No built-in support for version control systems
  • Auto-generated classes may not always meet specific requirements

Model First Approach

You start with designing entities and relationships with the help of Entity Developer visual ORM builder. This graphical interface allows you to create entities without writing code, after which Entity Framework generates both domain classes and the database schema.

Model First Approach

Advantages

  • Easy visual creation of entities and relationships
  • No coding required

Disadvantages

  • Auto-generated code may be less customizable
  • Limited control over database structure
  • Requires SQL expertise for modifications

Code First Approach

With this approach, you define domain classes first, and Entity Framework automatically generates the database tables. The Migration feature allows developers to manage schema changes through code.

Code First Approach

Advantages

  • Simplified database synchronization
  • Complete control over the code

Disadvantages

  • Requires programming experience
  • Some database objects cannot be created or deleted directly through EF

How Entity Framework works

One of the key advantages of Entity Framework is that it allows developers to work with data as domain-specific objects and properties. Developers can build applications focusing less on database tables and columns while writing less code.

Below is an overview of the Entity Framework workflow.

Overall Entity Framework workflow

Querying

With EDM in place, Entity Framework enables CRUD operations (Create, Read, Update, Delete). It translates LINQ to Entities queries into SQL commands for relational databases, ensuring efficient interactions. Additionally, it converts the database into entity objects.

Querying data with EF

Saving

When calling the SaveChanges() method, Entity Framework executes INSERT, UPDATE, or DELETE commands based on the state of entities. The Change Tracker monitors entity states and ensures that only modified data is saved to the database.

Entity Framework is a component of the .NET Framework. Therefore, applications created with this technology can run on any system with .NET Framework installed (version 3.5 SP1 or later).

Building an Entity Data Model

Entity Data Models (EDM) are an older approach to working with data which is outdated now, but can be used in certain scenarios with Entity Framework (not EF Core). An EDM represents the conceptual model, the storage model, and the mapping between them.

Entity Framework generates the conceptual model from domain classes, the context class, and default conventions. The storage model is derived from either domain classes (Code First) or an existing database (Database First). EF then automatically maps the conceptual model to the database schema.

Entity Data model

What is an entity

In Entity Framework, an Entity is a class that maps to a database table. This class must be included as a DbSet property in the DbContext class. Each entity refers to a table, and each property of an entity is a corresponding column in the database.

Entities can have two types of properties: Scalar properties and Navigation properties. Navigation properties are further divided into Reference Navigation and Collection Navigation properties.

Scalar properties

Scalar property is a primitive type (int, string, decimal, etc.). Each scalar property corresponds to a column in the database table, storing actual data.

Reference navigation properties

Reference navigation property is an entity property that references another entity type. It represents a one-to-one or many-to-one relationship in the database. For example, a Foreign Key column in one table that links to the Primary Key of another table is a Reference Navigation property.

Collection navigation properties

Collection navigation properties hold a collection of related entities representing one-to-many or many-to-many relationships. It is a collection of related entities stored as a generic collection (such as List<TEntity>). Entity Framework does not create a separate column for collection navigation properties in the related table. Instead, it establishes a linking column in the referenced entity's table.

Entity States

Entity Framework tracks the state of each entity throughout its lifecycle:

  • Added - new entity to be inserted into the database
  • Modified - an existing entity with updated values
  • Deleted - marked for removal
  • Unchanged - retrieved but not modified
  • Detached - not tracked by the context

Among these states, only the transition from Unchanged to Modified is automatically handled by the context. All other state changes require explicit actions using DbContext or DbSet methods.

The DbContext keeps references to all retrieved entities and tracks their states. This process, called Change Tracking, ensures proper management of all modifications to entity properties.

Migrations in EF Core

Migrations are the EF Core feature that allows developers to modify the data model and apply those changes to the database without dropping or recreating it. This way, we can ensure that the database schema is in sync with the EF model as domain classes evolve.

Whenever the developer updates domain classes, migrations update the database schema accordingly.

Key EF Core Migration commands:

Command Description
Add migration Creates a new migration with a snapshot of the current model.
Remove migration Deletes the most recent migration snapshot.
Update database Applies the latest migration updates to the database schema.
Script migration Generates an SQL script based on all migration snapshots.

ADO.NET data providers with EF Core support

ADO.NET is a data access technology developed by Microsoft that enables communication between relational databases and non-relational systems through components. Data providers built with ADO.NET allow developers to connect directly to data sources and retrieve and manage data. This way, ADO.NET acts as a bridge between applications and the database backend. It is the most efficient and straightforward method of accessing data within the .NET framework.

In application development, ADO.NET covers the following key tasks:

  • Connecting to the database
  • Opening the database connection
  • Setting up a record set to hold the necessary data
  • Retrieving the required data
  • Extracting the data and closing the connection

One notable solution in this space is Devart's dotConnect product line. High-performance ADO.NET-based data providers designed for popular databases and cloud data sources simplify the data-related .NET application development and allow developers to easily adapt its functionality to their specific needs.

dotConnect supports all major data sources.

How to work with EF Core visually

The professional version of dotConnect products comes in bundle with Entity Developer, a professional ORM designer that supports Entity Framework, Entity Framework Core, NHibernate, LinqConnect, Telerik Data Access, and LINQ to SQL. It integrates with Visual Studio and provides visualization for almost all mapping types.

Entity Developer supports both model-first and database-first approaches and allows developers to deploy changes between models and databases smoothly.

This tool connects to various data sources using Devart's dotConnect and open-source data providers. It provides visual editors for classes, properties, and other essential elements, helps the users design models and templates, ensures precise mapping for all supported ORMs, and generates code automatically.

Data Model in Entity Developer

Conclusion

Entity Framework Core (EF Core) is a favorite tool among many .NET developers. Since its introduction, developers have been able to reduce the amount of manually written SQL code by using .NET objects to interact with databases. With EF Core, accessing and managing data within applications became much more efficient.

Modern tools further enhance EF Core's functionality. dotConnect data providers, built with ADO.NET and coming in a bundle with the Entity Developer tool, allow developers to access data directly without additional clients. Thanks to its powerful visualization capabilities, Entity Developer makes .NET application development even more intuitive and efficient.

You can try dotConnect in your projects. Dedicated solutions are available for all major data sources, including relational databases and cloud platforms. Simply choose and download the provider with the Entity Developer, start the fully functional 30-day FREE TRIAL, and experience the difference.

Connect to Data Effortlessly in .NET

Streamline your .NET projects with feature-rich ADO.NET providers with ORM support

OSZAR »