Exploring the New Features in Entity Framework Core 7

Sohail Aslam
5 min readSep 6, 2023

--

Entity Framework Version 7.0

Introduction

Entity Framework Core (EF Core) has always been a popular choice for .NET developers when it comes to working with databases. With the recent release of .NET 7, EF Core has received significant enhancements and new features that make database operations even more efficient and flexible. In this article, we’ll take a deep dive into the latest improvements introduced in EF Core 7.

Getting Started with EF Core

Before we delve into the new features of EF Core 7.0, it’s essential to have a basic understanding of what EF Core is and how it works. If you’re new to ASP.NET Core development or need a refresher on ORM (Object Relational Mapping). This will provide you with a solid foundation for understanding the concepts we’ll discuss here.

The New ExecuteUpdate and ExecuteDelete Methods

One of the standout features in EF Core 7 is the introduction of two new methods: ExecuteUpdate and ExecuteDelete. These methods offer developers powerful tools for making changes to the database without the need to load entities into memory.

ExecuteUpdate: Effortless Updates

The ExecuteUpdate method allows you to update records in the database efficiently. Unlike the traditional SaveChanges method, which tracks changes to entities and sends updates to the database, ExecuteUpdate is explicit and precise. You specify which properties should be updated and their new values, resulting in performance gains.

Here’s an example of using ExecuteUpdate:

await db.Posts
.Where(p => p.Id == 4044)
.ExecuteUpdateAsync(s => s
.SetProperty(b => b.AuthorName, "Sohail Aslam")
.SetProperty(b => b.Title, "EF7 is here!")
.SetProperty(b => b.Text, "Some Text Here!")
.SetProperty(b => b.LastUpdateDate, "2023-09-06 17:29:46.5028235"));

This code updates specific properties of a Post entity with a matching ID without the need to load the entire entity into memory.

ExecuteDelete: Swift Deletions

Similarly, the ExecuteDelete method allows for the immediate deletion of entities from the database based on specified criteria. Whether you're deleting a single record or multiple records, ExecuteDelete performs deletions efficiently without entity loading.

Here are examples of using ExecuteDelete:

Deleting a single record:

await db.Posts.Where(p => p.Id == 4044).ExecuteDeleteAsync();

Deleting multiple records:

await db.Posts.Where(p => p?.Text.Contains("SomeText")).ExecuteDeleteAsync();

These methods provide developers with powerful tools for updating and deleting records while optimizing performance.

JSON Columns

JSON columns in relational databases have gained popularity for their flexibility in storing and querying semi-structured data. EF Core 7 introduces native support for JSON columns, allowing you to map .NET types to JSON documents. This feature provides a bridge between relational and NoSQL databases, offering a hybrid approach.

Mapping JSON Columns

Mapping .NET types to JSON columns is straightforward. Consider the following example:

public class Author
{
public Guid Id { get; set; }
public string? Name { get; set; }
public ContactDetails? Contact { get; set; }
}

public class ContactDetails
{
public Address Address { get; set; } = null!;
public string? Phone { get; set; }
}

public class Address
{
public string Street { get; set; }
public string City { get; set; }
public string Country { get; set; }
public string Postcode { get; set; }
}

By using the ToJson extension method in the OnModelCreating method, you can specify which table columns should receive JSON documents:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Author>().OwnsOne(
author => author.Contact, ownedNavigationBuilder =>
{
ownedNavigationBuilder.ToJson();
ownedNavigationBuilder.OwnsOne(contactDetails => contactDetails.Address);
});
}

This configuration allows .NET types to be converted to JSON documents when saved to the database, providing the best of both worlds.

Queries on JSON Columns

Working with JSON columns is seamless in EF Core 7. You can query JSON data using LINQ, just like you would with other data types. For instance, filtering records based on a property within a JSON document is straightforward:

var authorsByCity = await db.Authors.Where(author => author.Contact.Address.City == city).ToListAsync();

EF Core generates SQL code that extracts the JSON value from the Contact column, enabling you to work with JSON data effortlessly.

Updating JSON Columns

Updating JSON columns is a breeze with EF Core 7. You can use the familiar SaveChanges and SaveChangesAsync methods to update JSON documents. Whether you need to update the entire JSON object or specific properties within it, EF Core handles the task efficiently.

Here’s an example of updating an entire JSON document:

var authorExists = await db.Authors.Where(author => author.Id == id).FirstOrDefaultAsync();

authorExists.Contact = new()
{
Address = new("D-4/17", "Karachi", "Pakistan", "75000"),
Phone = "0304-2847198"
};
await db.SaveChangesAsync();

EF Core converts the object into JSON format and executes the necessary SQL to update the record.

Faster SaveChanges Method

Performance improvements are always welcome, and EF Core 7 delivers in this regard. The SaveChanges and SaveChangesAsync methods have been optimized to be up to four times faster than in EF Core 6.0. These enhancements result from reduced database round trips and faster SQL generation.

The SaveChanges method in EF Core 7 offers several advantages:

  • Batch multiple insert, update, and delete commands to minimize database round trips.
  • Handle explicit transactions and complex mappings efficiently.
  • Determine the order of entity inserts, updates, and deletes to avoid violating database constraints.
  • Efficiently manage database-generated values and primary key foreign key relationships.
  • Detect concurrency conflicts and support different database systems with efficient command generation.

These improvements make working with database changes more efficient and responsive.

New Query Options

EF Core 7 introduces new query options, including the ability to use GroupBy as the final operator in a query. This feature provides more flexibility when working with grouped data.

For example, you can use the GroupBy extension method to group entities:

var groupByAuthor = db.Posts.GroupBy(p => p.AuthorName).ToList();

While this type of GroupBy operation doesn't directly translate to SQL, EF Core performs grouping on the returned results, giving you greater control over your queries.

Conclusion

In conclusion, Entity Framework Core 7 has introduced a range of exciting features and enhancements that empower .NET developers to work with databases more efficiently and effectively. Whether you’re updating and deleting records without entity loading, harnessing the power of JSON columns, benefiting from faster SaveChanges methods, or exploring new query options, EF Core 7 opens up new possibilities for building robust and performant database-driven applications. Upgrade to EF Core 7 today to take advantage of these powerful features and improve your development workflow.

--

--