Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 21

Advanced EF Core 7

Course
Day 1: EF Core Overview
EF Core Overview
Abhishek Luv
Introducing Entity Framework Core 7
• Developers, including yours truly, have been struggling with mapping
data from a data source and code objects. But then ORM was
introduced.
• ORM stands for object-relational mapping and enables us to work with
domain objects and properties.
• The mapping struggle was over. Microsoft released Entity Framework
in 2008.
• Mapping is the part where you retrieve the data from the database
and put it in your own C# objects for further use. We did something
similar in ADO.NET:
Example
Introducing Entity Framework Core 7
• As usual, the newly released framework wasn’t widely accepted. It had
a lot of bugs and didn’t do what was expected.
• In 2010, Microsoft released a new version, which was a bit better.
• They kept building on it and now it’s one of the most common ORMs
when you use Microsoft programming languages (C#, VB, etc).
• The current version is Entity Framework Core 7.0.
What is Entity Framework Core
• Entity Framework Core (EF Core) is an open-source, lightweight, and
cross-platform version of Entity Framework data-access technology.
• It is an Object-Relational Mapper (ORM) tool that enables developers to
work with relational databases using .NET objects.
• It has been designed to be lightweight, and extensible and to support
cross-platform development as part of Microsoft's .NET Core
framework.
• It has also been designed to be simpler to use and to offer
performance improvements over previous versions of Entity
Framework.
What is Entity Framework Core
EF Core is an object-relational mapper (ORM). Object-relational mapping is a
technique that enables developers to work with data in an object-oriented
way by performing the work required to map between objects defined in an
application's programming language and data stored in relational data
sources.
• EF Core provides a set of APIs for managing database operations, such as
querying, inserting, updating, and deleting data, and it supports a wide
range of relational databases including SQL Server, MySQL, SQLite.
• EF Core supports LINQ (Language-Integrated Query), which allows
developers to write expressive and efficient queries using C#
• EF Core also provides a variety of performance-related features such as lazy
loading, change tracking, and caching.
• Additionally, it allows developers to use LINQ (Language Integrated Query)
to query and filter data, similar to how you would query an in-memory
collection.
Why use an ORM
• An ORM (Object-Relational Mapper) is used to interact with a database
using an object-oriented programming language. ORMs allow
developers to work with databases using familiar, object-oriented
concepts, rather than writing raw SQL statements.
• Provide features such as caching, lazy loading, and connection pooling,
which can improve application performance.
• They also provide an abstraction layer between the application and the
database, so that the application code can be insulated from changes to
the underlying database schema.
• This can make it easier to switch to a different database in the future or
to improve scalability by distributing the data across multiple servers.
• Overall, ORMs can help improve developer productivity, code
maintainability, and application performance.
Entity Framework Core Features
• Cross-platform: EF Core can be used on a variety of platforms including
Windows, Linux, and Mac.
• Lightweight: EF Core has a smaller footprint and fewer dependencies
than the full version of Entity Framework.
• Code first: EF Core allows developers to create a database from code,
which enables a more agile and test-driven development workflow.
• LINQ support: EF Core supports LINQ, a powerful and expressive query
language, which allows developers to write efficient and readable
queries using C#.
• Support for multiple databases: EF Core supports a wide range of
relational databases including SQL Server, MySQL, SQLite, and
PostgreSQL.
Entity Framework Core Features
• Migrations: EF Core has built-in support for creating and managing
database migrations, which allows for easy management of database
changes over time.
• Performance improvements: EF Core has been optimized for
performance and can handle large datasets efficiently.
• Relationships: Support for one-to-one, one-to-many, and many-to-
many
• Inheritance: Support for TPC, TPH, and TPT
• Support for Lazy, Eager, and Explicit loading, change tracking, and
caching.
Approaches in Entity Framework Core
• EF Core has two ways of managing your database. The first one is code
first and the other one is the database first. There is a big difference
between them, but code first is the most used.
• Database first is used when there is already a database present and
the database will not be managed by code.
• Code first is used when there is no current database, but you want to
create one.
• Code-First is mainly useful in Domain Driven Design.
• In the Code-First approach, you focus on the domain of your
application and start creating classes for your domain entity rather
than design your database first and then create the classes which
match your database design.
Approaches in Entity Framework Core
• EF Core does not support visual designer for DB model and wizard to
create the entity and context classes similar to EF 6. So, we need to do
reverse engineering using the Scaffold-DbContext command.
• This reverse engineering command creates entity and context classes
(by deriving from DbContext) based on the schema of the existing
database. We will look at this topic in detail later on.
How to get Entity Framework Core
Install EF Core by downloading the below shown Nuget Packages:
• Microsoft.EntityFrameworkCore
• Microsoft.EntityFrameworkCore.SqlServer
• Microsoft.EntityFrameworkCore.Tools
EF Core is available as a Nuget Package that can be added to your
project in many ways depending on the project type and the tools
available to you.
• Visual Studio Package manager UI
• Package Manager console: Install-Package packageName
• Command Line Tools: dotnet add package packageName
• By Adding/Removing Package names in YourProject.csproj file
The DbContext class of EF Core
• The EF Core DbContext class represents a session with a database and
provides an API for communicating with the database with the
following capabilities:
• Database Connections
• Data operations such as querying and persistence
• Model building
• Change Tracking
• Caching
• Transaction management
The DbContext lifetime
The lifetime of a DbContext begins when the instance is created and ends when the
instance is disposed. A DbContext instance is designed to be used for a single unit-of-
work.
This means that the lifetime of a DbContext instance is usually very short.
A typical unit-of-work when using Entity Framework Core (EF Core) involves:
• Creation of a DbContext instance
• Tracking of entity instances by the context.
• SaveChanges is called. EF Core detects the changes made and writes them to the
database.
• The DbContext instance is disposed.
DbContext is not thread-safe
• DbContext is not thread-safe. Do not share contexts between threads. Make sure to
await all async calls before continuing to use the context instance.
• The AddDbContext extension method registers DbContext types with a scoped
lifetime by default.
• This is safe from concurrent access issues in most ASP.NET Core applications
because there is only one thread executing each client request at a given time, and
because each request gets a separate dependency injection scope (and therefore a
separate DbContext instance).
DbContext in DI for ASP.NET Core
• In many web applications, each HTTP request corresponds to a single unit-of-work.
This makes tying the context lifetime to that of the request a good default for web
applications.
• ASP.NET Core applications are configured using dependency injection. EF Core can be
added to this configuration using AddDbContext in the `Program.cs` file.
DbContext in DI for ASP.NET Core
• The ApplicationDbContext class must expose a public constructor with a
DbContextOptions<ApplicationDbContext> parameter.

• ApplicationDbContext can then be used in ASP.NET Core controllers or other services


through constructor injection. For example:
• The final result is an ApplicationDbContext instance created for each request and
passed to the controller to perform a unit-of-work before being disposed when the
request ends.
Simple DbContext with new keyword
• DbContext instances can be constructed in the normal .NET way, for example with
new in C#. Configuration can be performed by overriding the OnConfiguring method,
or by passing options to the constructor.

• This pattern also makes it easy to pass configuration like the connection string via the
DbContext constructor. For example:
Avoiding DbContext threading issues
• Entity Framework Core does not support multiple parallel operations being run on
the same DbContext instance. This includes both parallel execution of async queries
and any explicit concurrent use from multiple threads.
• Therefore, always await async calls immediately, or use separate DbContext
instances for operations that execute in parallel.
• When EF Core detects an attempt to use a DbContext instance concurrently, you'll
see an InvalidOperationException with a message like this:
• A second operation started on this context before a previous operation completed.
This is usually caused by different threads using the same instance of DbContext,
however instance members are not guaranteed to be thread safe.
• Always await EF Core asynchronous methods immediately.
Thanks for joining!
Abhishek Luv

You might also like