Slot 21_22-Working with Databases Using Entity Framework Core
Slot 21_22-Working with Databases Using Entity Framework Core
EF Core allows us to interact with data from relational databases using an
object model that maps directly to the business objects (or domain objects) in
our application
EF Core can serve as an object-relational mapper (O/RM), which:
Eliminates the need for most of the data-access code that typically needs to be written
05/17/2025 5
Understanding Entity Framework Core
EF Core 5.0 runs on platforms that support .NET Standard 2.1, meaning .NET
Core 3.0 and 3.1, as well as .NET 5. It will not run on.NET Standard 2.0
platforms like .NET Framework 4.8
Entity Framework Core supports many database providers to access different
databases and perform database operations:
SQL Server (www.nuget.org/packages/Microsoft.EntityFrameworkCore.SqlServer)
MySQL (www.nuget.org/packages/MySQL.Data.EntityFrameworkCore)
PostgreSQL (www.nuget.org/packages/Npgsql.EntityFrameworkCore.PostgreSQL)
SQLite (www.nuget.org/packages/Microsoft.EntityFrameworkCore.Sqlite)
Oracle (www.nuget.org/packages/Oracle.ManagedDataAccess.Core)
In-memory (www.nuget.org/packages/Microsoft.EntityFrameworkCore.InMemory)
More database provider: https://docs.microsoft.com/en-us/ef/core/providers/
05/17/2025 6
Understanding Entity Framework Core
To manage data in a specific database, we need classes that know how to
EF Core database providers are sets of classes that are optimized for a
specific data store. There is even a provider for storing the data in the memory
of the current process, which is useful for high performance unit testing since it
MySQL MySQL.Data.EntityFrameworkCore
In-memory Microsoft.EntityFrameworkCore.InMemory
Entity Framework Core provides faster execution speeds, especially when
reading data (almost the same performance as manually copying data from a
DataReader object to a typed .NET object)
Batching allows the Entity Framework Core to merge INSERT, DELETE, and
UPDATE operations into one database management system round-trip rather
than sending each command one at a time
05/17/2025 12
New Features in Entity Framework Core
Projections with Select() can now be mapped directly to entity classes. The
detour via anonymous .NET objects is no longer necessary
Default values for columns in the database are now supported in both reverse
engineering and forward engineering
In addition to the classic auto-increment values, newer methods such as
sequences are now also allowed for key generation
The term shadow properties in Entity Framework Core refers to the now
possible access to columns of the database table for which there are no
attributes in the class
05/17/2025 13
Process Models for Entity Framework Core
Entity Framework Core supports the following:
Reverse engineering of existing databases (an object model is created from
an existing database schema)
Forward engineering of databases (a database schema is generated from an
object model)
Reverse engineering (often referred to as database first) is useful if we already
have a database or if developers choose to create a database in a traditional
way
The second option, called forward engineering, gives the developer the ability
to design an object model. From this, the developer can then generate a
database schema
05/17/2025 14
Process Models for Entity Framework Core
For the developer, forward engineering is usually better because we can
design an object model that we need for programming
Forward engineering can be used at development time (via so-called
schema migrations) or at runtime
A schema migration is the creation of the database with an initial schema
or a later extension/modification of the schema
05/17/2025 15
Forward engineering versus reverse engineering for Entity Framework Core
05/17/2025 16
Components of Entity Framework Core
Entity classes (domain object classes, business object classes, data classes,
or persistent classes) are representations of tables and views. They contain
properties or fields that are mapped to columns of the tables/views
Entity classes can be plain old CLR objects (POCO classes); in other words,
they need no base class and no interface
A context class is a class always derived from the DbContext base class. It
has properties of type DbSet for each of the entity classes
The context class or DbSet properties take the commands of the self-created
program code in the form of LINQ commands, SQL commands, stored
procedure and table-valued function (TVF) calls, or special API calls for
append, modify, and delete
05/17/2025 17
Components of Entity Framework Core
The context class sends the
commands to the DBMS-specific
provider, which sends the
commands to the database via
DbCommand objects and
receives result sets in a
DataReader from the database
The context class transforms the
contents of the DataReader
object into instances of the entity
class. This process is called
materialization The central artifacts in Entity Framework Core and their context
05/17/2025 18
DbContext Class
The DbContext doesn’t get used directly, but through classes that inherit from
the DbContext class
The entities that are mapped to the database are added as DbSet<T>
properties on the derived class
The OnModelCreating method is used to further define the mappings between
the entities and the database
The following table shows some of the more commonly used members of the DbContext:
05/17/2025 19
Member of DbContext Description
Provides access to database-related information and functionality, including execution
Database
of SQL statements
The metadata about the shape of entities, the relationships between them, and how
Model
they map to the database. Note: This property is usually not interacted with directly
Provides access to information and operations for entity instances this context is
ChangeTracker
tracking
Used to query and save instances of application entities. LINQ queries against DbSet
DbSet<T>
properties are translated into SQL queries
Provides access to change tracking information and operations (such as changing the
EntryEntry<TEntity> EntityState) for the entity. Can also be called on an untracked entity to change the
state to tracked
SaveChanges/SaveChangesAsync Saves all entity changes to the database and returns the number of records affected
A builder used to create or modify options for the context. Executes each time a
DbContext instance is created. Note: It is recommended not to use this, and instead
OnConfiguring
use the DbContextOptions to configure the context at runtime, and use an instance of
the IDesignTimeDbContextFactory at design time
Called when a model has been initialized, but before it’s finalized. Methods from the
OnModelCreating
Fluent API are placed in this method to finalize the shape of the model
05/17/2025 20
DbSet Class
For each entity in our object model, we add a property of type DbSet<T>. The
DbSet<T> is a specialized collection property used to interact with the
database provider to get, add, update, or delete records in the database
Each DbSet<T> provides a number of core services to each collection, such as
creating, deleting, and finding records in the represented table
The following table describes some of the core members of the DbSet<T>
class:
05/17/2025 21
The following table describes some of the core members of the DbSet<T> class:
Member of DbSet<T> Description
Begins tracking the entity/entities in the Added state. Item(s) will be added
Add/AddRange
when SaveChanges is called. Async versions are available as well
Searches for the entity in the ChangeTracker by primary key. If not found,
Find the data store is queried for the object. An async version is available as
well
Begins tracking the entity/entities in the Modified state. Item(s) will be
Update/UpdateRange updated when SaveChanges is called. Async versions are available as
well
Begins tracking the entity/entities in the Deleted state. Item(s) will be
Remove/RemoveRange removed when SaveChanges is called. Async versions are available as
well
Begins tracking the entity/entities in the Unchanged state. No operation
Attach/AttachRange will execute when SaveChanges is called. Async versions are available
as well
05/17/2025 22
Entities
Entities are a conceptual model of a physical database that maps to our
business domain. This model is termed an entity data model (EDM). The EDM
is a client-side set of classes that are mapped to a physical database by Entity
Framework Core convention and configuration
05/17/2025 23
Defining Entity Framework Core Models
An entity class represents the structure of a table and an instance of the class
EF Core uses a combination of Conventions, Annotation Atributes, and
Fluent API statements to build an entity model at runtime so that any actions
05/17/2025 26
Data Annotations Supported by the Entity Framework
Data Annotation Description
Table Defines the schema and table name for the entity
Column Defines the column name for the model property
Key Defines the primary key for the model. Key fields are implicitly also [Required]
Required Declares the property as not nullable in the database
ForeignKey Declares a property that is used as the foreign key for a navigation property
InverseProperty Declares the navigation property on the other end of a relationship
StringLength Specifies the max length for a string property
Declares a type as a rowversion in SQL Server and adds concurrency checks to database
TimeStamp
operations involving the entity
ConcurrencyCheck Flags field to be used in concurrency checking when executing updates and deletes
Specifies if the field is database generated or not. Takes a DatabaseGeneratedOption value
DatabaseGenerated
of Computed, Identity, or None
DataType Provides for a more specific definition of a field than the intrinsic datatype
NotMapped Excludes the property or class in regard to database fields and tables
05/17/2025 27
Defining Entity Framework Core Models
EF Core Fluent API: The Fluent API configures the application entities through
C# code. The methods are exposed by the ModelBuilder instance available in the
DbContext, OnModelCreating method
The Fluent API is the most powerful of the configuration methods and overrides any
data annotations or conventions that are in conflict. Some of the configuration options
are only available using the Fluent API, such as complex keys and indices
For example, the maximum length of a ProductName is 40 , and the value cannot be
null, we could apply Fluent API Fluent API statement in the OnModelCreating method
of a database context class, as shown in the following code:
05/17/2025 28
The EF Core Global Tool CLI Commands
The dotnet-ef global CLI tool EF Core tooling contains the commands
needed to scaffold existing databases into code, to create/remove migrations
(changes in the data structure based on the entities), and to operate on a
database (update, drop, etc.)
Open Command Prompt (or Terminal) then run as the following command:
Check if we have already installed dotnet-ef as a global tool
05/17/2025 29
The EF Core Global Tool CLI Commands
If an old version is already installed, then uninstall the tool, as shown in the
following command:
05/17/2025 30
The EF Core Global Tool CLI Commands
The three main commands in the EF Core global tool are shown in the following
table:
Command Description
Database Commands to manage the database. Sub-commands include drop and update
Commands to manage the DbContext types. Sub-commands include scaffold, list, and
DbContext
info
Migrations Commands to manage migrations. Sub-commands include add, list, remove, and script
Each main command has additional sub-commands. As with the all of the .NET
Core commands, each command has a rich help system that can be accessed
by entering -h along with the command
05/17/2025 31
Reverse Engineering of Existing
Databases Demonstration
05/17/2025 32
Create a sample database named MyStore for demonstrations
05/17/2025 33
1.Create a Console App named DemoDatabaseFirst then right-click on project , select
Open In Terminal to install packages
05/17/2025 34
2.On Developer PowerShell dialog , execute the following commands to install packages:
dotnet add package Microsoft.EntityFrameworkCore.design
3.On Developer PowerShell dialog , execute the following commands to generate model:
05/17/2025 35
05/17/2025 36
MyStoreConext Class
05/17/2025 37
05/17/2025 38
4.Write codes for Program.cs then run project
05/17/2025 39
The Weaknesses Reverse Engineering
In the case of the temporal tables (called system-versioned tables) added in
SQL Server , the history tables cannot be mapped using Entity Framework
Core (this is already possible for the actual table)
For database views and stored procedures, in contrast to the classic Entity
Framework, classes and functions cannot be generated
Once the object model is generated using the Entity Framework Core
commandline tools, we cannot update it
The Update Model from Database command available for the Database First
approach is currently not implemented
05/17/2025 40
Forward Engineering for New Databases
Forward engineering is available in the classic Entity Framework in two
variants: Model First and Code First
In Model First, we graphically create an entity data model (EDM) to generate
the database schema and .NET classes
In Code First, we write classes directly, from which the database schema is
created
The EDM is invisible. In the redesigned Entity Framework Core, there is only
the second approach, which however is not called Code First but code-based
modeling and no longer uses an invisible EDM
05/17/2025 41
Forward Engineering for New Databases
Code-based modeling in Entity Framework Core happens through these two
types of classes:
We create entity classes, which store the data in RAM. We create navigation
properties in the entity classes that represent the relationships between the
entity classes. These are typically plain old CRL objects (POCOs) with
properties for each database column
05/17/2025 42
Forward Engineering for New
Databases Demonstration
05/17/2025 43
1.Create a Winform app named ManageCategoriesApp includes a form named
frmManageCategories and has controls as follows :
Object Type Object name Properties / Events
Label lbCategoryID Text: lbCategoryID
Label lbCategoryName Text: CategoryName
TextBox txtCategoryID ReadOnly: True
TextBox txtCategoryName
Button btnInsert Text: Insert
Event Handler: Click
Button btnUpdate Text: Update
Event Handler: Click
Button btnDelete Text: Delete
Event Handler: Click
DataGridView dgvCategories ReadOnly: True
SelectionMode:FullRowSelect
Form frmManageCategories StartPosition: CenterScreen
Text: Manage Categories
Event Handler: Load
05/17/2025 44
2.Right-click on the project | Add | New Item, select JavaScript JSON Configuration File
then rename to appsettings.json , click Add and write contents as follows:
{
"ConnectionStrings": {
"MyStockDB":
"Server=(local);uid=sa;pwd=123;database=MyStockDB"
}
}
Next , right-click on appsettings.json | Properties, select Copy if newer
05/17/2025 45
3.Install the following packages from Nuget
05/17/2025 46
5.Write codes MyStockDBContext.cs as follows:
05/17/2025 47
6.Right-click on the project, select Open in Terminal. On Developer PowerShell dialog ,
execute the following commands to generate database:
dotnet ef migrations add "Initial"
dotnet ef database update
05/17/2025 48
6. Write codes ManageCategories.cs as follows:
05/17/2025 49
05/17/2025 50
05/17/2025 51
8.Write codes in frmManageCategories.cs as follows then press Ctrl+F5 to run project:
05/17/2025 52
05/17/2025 53
Querying EF Core Models
Entity Framework Core allows us to write database queries with Language
Integrated Query (LINQ)
The starting point for all LINQ queries in Entity Framework Core is the context
class that we create either during the reverse engineering of an existing
database or manually while forward engineering
The context class in Entity Framework Core always inherits from the base class
Microsoft.EntityFrameworkCore.DbContext. Accordingly, we have to use
DbContext for all LINQ operations
The DbContext class implements the IDisposable interface. As part of the
Dispose() method, DbContext frees all allocated resources, including
references to all objects loaded with change tracking
05/17/2025 54
LINQ Queries
After instantiating the context class, we can formulate a LINQ query. This query
is not necessarily executed immediately; it is initially in the form of an object with
the interface IQueryable<T>
The LINQ query is executed when the result is actually used (for example, in a
foreach loop) or when converted to another collection type
We can force the execution of the query with a LINQ conversion operator with
ToList(), ToArray(), ToLookup(), ToDictionary(), Single(), SingleOrDefault(),
First(), FirstOrDefault(), or an aggregate operator such as Count(), Min(), Max(),
or Sum()
05/17/2025 55
Internals for running a LINQ
command through Entity
Framework Core
05/17/2025 56
LINQ Queries Demonstrations
(using Reverse Engineering of Existing Databases Demo)
05/17/2025 57
Create a query for categories that have products with that minimum number of units in
stock. Enumerate through the categories and products, outpuing the name and units in
stock for each one (using Reverse Engineering of Existing Databases Demonstration)
05/17/2025 58
Create a query for products that cost more than the price
05/17/2025 59
Perform aggregation functions, such as Average and Sum on the Products table
05/17/2025 60
Lab and Assigment
1. Do Hands-on Lab:
2. Do Assigment:
Assignment_02_SalesManagement.pdf
05/17/2025 61
Summary
Concepts were introduced:
Overview Entity Framework Core(EF Core)
Explain components inside Entity Framework Core
Explain about Database First Model and Code Model
Explain about Manipulating data with EF Core
Demo create accessing database by Entity Framework Core using Database First
Model
Demo create accessing database by Entity Framework Core using Code Model
Demo using LINQ Queries in Entity Framework Core
62