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
- What’s New in EF Core 5 Preview 7
- Prerequisites
- How to get EF Core 5.0 previews
- Installing the EF Core Command Line Interface (CLI)
- Daily builds
- Contribute to .NET 5
- The EF Core Community Standup
- Documentation and Feedback
- Helpful Short Links
- Thank you from the team
- Thank you to our contributors!
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.
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.
- Visit the .NET Community Standup page to preview upcoming shows and view recordings from past shows
- Suggest a guest or project, including your own by posting to the linked discussion
- You can also request an EF Core demo
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.
Helpful Short Links
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!
Arthur Vickers |
Andriy Svyryd |
Brice Lambson |
Jeremy Likness |
lajones |
Maurycy Markowski |
Shay Rojansky |
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).
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″
Hi, unfortunately that feature missed preview 7 but it is available in the nightly builds.