Announcing Entity Framework Core EF Core 5.0 Preview 7

Jeremy Likness

Today, the Entity Framework Core team announces the seventh preview release of EF Core 5.0. This release includes a factory to create DbContext instances, the ability to reset DbContext state, Cosmos DB improvements including enhanced support for configuration options and partition keys, and much more.

In this post

We especially would like to share our deepest appreciation for the many contributors who help make this project better every day. Thank you!


What's New in EF Core 5 Preview 7

We maintain documentation covering new features introduced into each preview.

Some of the highlights from preview 7 are called out below. This preview also includes several bug fixes.

DbContextFactory

EF Core 5.0 introduces AddDbContextFactory and AddPooledDbContextFactory to register a factory for creating DbContext instances in the application's dependency injection (D.I.) container. For example:

services.AddDbContextFactory<SomeDbContext>(b =>
    b.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=Test"));

Application services such as ASP.NET Core controllers can then depend on IDbContextFactory<TContext> in the service constructor. For example:

public class MyController
{
    private readonly IDbContextFactory<SomeDbContext> _contextFactory;

    public MyController(IDbContextFactory<SomeDbContext> contextFactory)
    {
        _contextFactory = contextFactory;
    }
}

DbContext instances can then be created and used as needed. For example:

public void DoSomehing()
{
    using (var context = _contextFactory.CreateDbContext())
    {
        // ...            
    }
}

Note that the DbContext instances created in this way are not managed by the application's service provider and therefore must be disposed by the application. This decoupling is very useful for Blazor applications, where using IDbContextFactory is recommended, but may also be useful in other scenarios.

DbContext instances can be pooled by calling AddPooledDbContextFactory. This pooling works the same way as for AddDbContextPool, and also has the same limitations.

Documentation is tracked by issue #2523.

Reset DbContext state

EF Core 5.0 introduces ChangeTracker.Clear() which clears the DbContext of all tracked entities. This should usually not be needed when using the best practice of creating a new, short-lived context instance for each unit-of-work. However, if there is a need to reset the state of a DbContext instance, then using the new Clear() method is more performant and robust than mass-detaching all entities.

Documentation is tracked by issue #2524.

New pattern for store-generated defaults

EF Core allows an explicit value to be set for a column that may also have default value constraint. EF Core uses the CLR default of type property type as a sentinel for this; if the value is not the CLR default, then it is inserted, otherwise the database default is used.

This creates problems for types where the CLR default is not a good sentinel–most notably, bool properties. EF Core 5.0 now allows the backing field to be nullable for cases like this. For example:

public class Blog
{
    private bool? _isValid;

    public bool IsValid
    {
        get => _isValid ?? false;
        set => _isValid = value;
    }
}

Note that the backing field is nullable, but the publicly exposed property is not. This allows the sentinel value to be null without impacting the public surface of the entity type. In this case, if the IsValid is never set, then the database default will be used since the backing field remains null. If either true or false are set, then this value is saved explicitly to the database.

Documentation is tracked by issue #2525.

Savepoints

EF Core now supports savepoints for greater control over transactions that execute multiple operations.

Savepoints can be manually created, released, and rolled back. For example:

context.Database.CreateSavepoint("MySavePoint");

In addition, EF Core will now roll back to the last savepoint when executing SaveChanges fails. This allows SaveChanges to be re-tried without re-trying the entire transaction.

Documentation is tracked by issue #2429.

Cosmos partition keys

EF Core allows the Cosmos partition key is included in the EF model. For example:

modelBuilder.Entity<Customer>().HasPartitionKey(b => b.AlternateKey)

Starting with preview 7, the partition key is included in the entity type's PK and is used to improved performance in some queries.

Documentation is tracked by issue #2471.

Cosmos configuration

EF Core 5.0 improves configuration of Cosmos and Cosmos connections.

Previously, EF Core required the end-point and key to be specified explicitly when connecting to a Cosmos database. EF Core 5.0 allows use of a connection string instead. In addition, EF Core 5.0 allows the WebProxy instance to be explicitly set. For example:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    => optionsBuilder
        .UseCosmos("my-cosmos-connection-string", "MyDb",
            cosmosOptionsBuilder =>
            {
                cosmosOptionsBuilder.WebProxy(myProxyInstance);
            });

Many other timeout values, limits, etc. can now also be configured. For example:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    => optionsBuilder
        .UseCosmos("my-cosmos-connection-string", "MyDb",
            cosmosOptionsBuilder =>
            {
                cosmosOptionsBuilder.LimitToEndpoint();
                cosmosOptionsBuilder.RequestTimeout(requestTimeout);
                cosmosOptionsBuilder.OpenTcpConnectionTimeout(timeout);
                cosmosOptionsBuilder.IdleTcpConnectionTimeout(timeout);
                cosmosOptionsBuilder.GatewayModeMaxConnectionLimit(connectionLimit);
                cosmosOptionsBuilder.MaxTcpConnectionsPerEndpoint(connectionLimit);
                cosmosOptionsBuilder.MaxRequestsPerTcpConnection(requestLimit);
            });

Finally, the default connection mode is now ConnectionMode.Gateway, which is generally more compatible.

Documentation is tracked by issue #2471.

Scaffold-DbContext now singularizes

Previously when scaffolding a DbContext from an existing database, EF Core will create entity type names that match the table names in the database. For example, tables People and Addresses resulted in entity types named People and Addresses.

In previous releases, this behavior was configurable through registration of a pluralization service. Now in EF Core 5.0, the Humanizer package is used as a default pluralization service. This means tables People and Addresses will now be reverse engineered to entity types named Person and Address.


Prerequisites

EF Core 5.0 will not run on .NET Standard 2.0 platforms, including .NET Framework.

  • The previews of EF Core 5.0 require .NET Standard 2.1.
  • This means that EF Core 5.0 will run on .NET Core 3.1 and does not require .NET 5.

To summarize: EF Core 5.0 runs on platforms that support .NET Standard 2.1.

The plan is to maintain .NET Standard 2.1 compatibility through the final release.

How to get EF Core 5.0 previews

EF Core is distributed exclusively as a set of NuGet packages. For example, to add the SQL Server provider to your project, you can use the following command using the dotnet tool:

dotnet add package Microsoft.EntityFrameworkCore.SqlServer --version 5.0.0-preview.7.20365.15

This following table links to the preview 7 versions of the EF Core packages and describes what they are used for.

Package Purpose
Microsoft.EntityFrameworkCore The main EF Core package that is independent of specific database providers
Microsoft.EntityFrameworkCore.SqlServer Database provider for Microsoft SQL Server and SQL Azure
Microsoft.EntityFrameworkCore.SqlServer.NetTopologySuite SQL Server support for spatial types
Microsoft.EntityFrameworkCore.Sqlite Database provider for SQLite that includes the native binary for the database engine
Microsoft.EntityFrameworkCore.Sqlite.Core Database provider for SQLite without a packaged native binary
Microsoft.EntityFrameworkCore.Sqlite.NetTopologySuite SQLite support for spatial types
Microsoft.EntityFrameworkCore.Cosmos Database provider for Azure Cosmos DB
Microsoft.EntityFrameworkCore.InMemory The in-memory database provider
Microsoft.EntityFrameworkCore.Tools EF Core PowerShell commands for the Visual Studio Package Manager Console; use this to integrate tools like scaffolding and migrations with Visual Studio
Microsoft.EntityFrameworkCore.Design Shared design-time components for EF Core tools
Microsoft.EntityFrameworkCore.Proxies Lazy-loading and change-tracking proxies
Microsoft.EntityFrameworkCore.Abstractions Decoupled EF Core abstractions; use this for features like extended data annotations defined by EF Core
Microsoft.EntityFrameworkCore.Relational Shared EF Core components for relational database providers
Microsoft.EntityFrameworkCore.Analyzers C# analyzers for EF Core

We also published the 5.0 preview 7 release of the Microsoft.Data.Sqlite.Core provider for ADO.NET.

Installing the EF Core Command Line Interface (CLI)

As with EF Core 3.0 and 3.1, the EF Core CLI is no longer included in the .NET Core SDK. Before you can execute EF Core migration or scaffolding commands, you'll have to install this package as either a global or local tool.

dotnet-ef

To install the preview tool globally, first uninstall any existing version with:

dotnet tool uninstall --global dotnet-ef

Then install with:

dotnet tool install --global dotnet-ef --version 5.0.0-preview.7.20365.15

It's possible to use this new version of the EF Core CLI with projects that use older versions of the EF Core runtime.


Daily builds

EF Core previews are aligned with .NET 5 previews. These previews tend to lag behind the latest work on EF Core. Consider using the daily builds instead to get the most up-to-date EF Core features and bug fixes.

As with the previews, the daily builds do not require .NET 5; they can be used with GA/RTM release of .NET Core 3.1.


Contribute to .NET 5

The .NET documentation team is reorganizing .NET content to better match the workloads you build with .NET. This includes a new .NET Data landing page that will link out to data-related topics ranging from EF Core to APIs, Big Data, and Machine learning. The planning and execution will be done completely in the open on GitHub. This is your opportunity to help shape the hierarchy and content to best fit your needs as a .NET developer. We look forward to your contributions!

The EF Core Community Standup

The EF Core team is now live streaming every other Wednesday at 10am Pacific Time, 1pm Eastern Time, or 17:00 UTC. Join the stream to ask questions about the EF Core topic of your choice, including the latest preview release.

Documentation and Feedback

The starting point for all EF Core documentation is docs.microsoft.com/ef/.

Please file issues found and any other feedback on the dotnet/efcore GitHub repo.

The following short links are provided for easy reference and access.

Main documentation: https://aka.ms/efdocs

Issues and feature requests for EF Core: https://aka.ms/efcorefeedback

Entity Framework Roadmap: https://aka.ms/efroadmap

What's new in EF Core 5.x? https://aka.ms/efcore5


Thank you from the team

A big thank you from the EF team to everyone who has used EF over the years!

ajcvickers
Arthur Vickers
AndriySvyryd
Andriy Svyryd

Brice Lambson
JeremyLikness
Jeremy Likness
lajones
lajones
maumar
Maurycy Markowski
roji
Shay Rojansky
smitpatel
Smit Patel

Thank you to our contributors!

A big thank you to the following community members who have already contributed code or documentation to the EF Core 5 release! (List is in chronological order of first contribution to EF Core 5).

aevitas
aevitas
alaatm
Alaa Masoud
aleksandar-manukov
Aleksandar Manukov
amrbadawy
Amr Badawy
AnthonyMonterrosa
Anthony Monterrosa
bbrandt
Ben Brandt
benmccallum
Ben McCallum
ccjx
Clarence Cai
CGijbels
Christophe Gijbels
cincuranet
Jiri Cincura
Costo
Vincent Costel
dshuvaev
Dmitry Shuvaev
EricStG
Eric St-Georges
ErikEJ
Erik Ejlskov Jensen
gravbox
Christopher Davis
ivaylokenov
Ivaylo Kenov
jfoshee
Jacob Foshee
jmzagorski
Jeremy Zagorski
jviau
Jacob Viau
knom
Max K.
lohoris-crane
lohoris-crane
loic-sharma
Loïc Sharma
lokalmatador
lokalmatador
mariusGundersen
Marius Gundersen
Marusyk
Roman Marusyk
matthiaslischka
Matthias Lischka
MaxG117
MaxG117
MHDuke
MHDuke
mikes-gh
Mike Surcouf
Muppets
Neil Bostrom
nmichels
Nícolas Michels
OOberoi
Obi Oberoi
orionstudt
Josh Studt
ozantopal
Ozan Topal
pmiddleton
Paul Middleton
prog-rajkamal
Raj
ptjhuang
Peter Huang
ralmsdeveloper
Rafael Almeida Santos
redoz
Patrik Husfloen
rmarskell
Richard Marskell
sguitardude
sguitardude
SimpleSamples
Sam Hobbs
svengeance
Sven
VladDragnea
Vlad
vslee
vslee
WeihanLi
liweihan
Youssef1313
Youssef Victor
1iveowl
1iveowl
thomaslevesque
Thomas Levesque
akovac35
Aleksander Kovač
leotsarev
Leonid Tsarev
kostat
Konstantin Triger
sungam3r
Ivan Maximov
dzmitry-lahoda
Dzmitry Lahoda
Logerfo
Bruno Logerfo
witheej
Josh Withee
FransBouma
Frans Bouma
IGx89
Matthew Lieder
paulomorgado
Paulo Morgado
mderriey
Mickaël Derriey
LaurenceJKing
Laurence King
oskarj
Oskar Josefsson
bdebaere
bdebaere
BhargaviAnnadevara-MSFT
Bhargavi Annadevara
AlexanderTaeschner
Alexander Täschner
Jesse-Hufstetler
Jesse Hufstetler
ivarlovlie
Ivar Løvlie
cucoreanu
cucoreanu
serpent5
Kirk Larkin
sdanyliv
Svyatoslav Danyliv
twenzel
Toni Wenzel
manvydasu
manvydasu
brandongregoryscott
Brandon Scott
uncheckederror
Thomas Ryan
rocke97
Aaron Gunther
jonlouie
Jon Louie
mohsinnasir
Mohsin Nasir
seekingtheoptimal
Bálint Szabó
MartinBP
Martin Boye Petersen
Ropouser
Duje Đaković
codemillmatt
Matt Soucoup
shahabganji
Saeed Ganji
AshkanAbd
Ashkan Abd
 

2 comments

Discussion is closed. Login to edit/delete existing comments.

  • Andres 0

    EF Core 5.0 introduces AddDbContextFactory and AddPooledDbContextFactory to register a factory for creating DbContext instances

    AddPooledDbContextFactory seems to be missing?
    I can use AddDbContextFactory. When I press F12, Microsoft.Extensions.DependencyInjection doesn’t contain AddPooledDbContextFactory.
    Microsoft.Extensions.DependencyInjection Version=”5.0.0-preview.7.20364.11″

    • Jeremy LiknessMicrosoft employee 0

      Hi, unfortunately that feature missed preview 7 but it is available in the nightly builds.

Feedback usabilla icon