EF Core 11 new features: FullJoin, MinBy, MaxBy and split queries

David Grace David Grace

EF Core 11 has fixes for problems that developers have waited years for. The new features in .NET 11 will save you time when writing queries, but there is one I wouldn't trust.

Full join support

.NET 10 gave you support for left join and right join, but there was no full join support.

A full join is useful when you want to bring two sets of data together and keep the rows that don't match. For example, you might want customers who haven't placed any orders and orders that don't belong to a customer, all in one result.

Writing a full join in .NET 10

If you wanted to write a full join query in EF Core 10, you had to write two separate queries. The first query uses LeftJoin to get the customers with their orders. The second query uses RightJoin and filters it down to the orders that don't have a customer. Then you join the two queries together using Concat.

// OrderRepository.cs
public async Task<IList<GetCustomerOrderDto>> GetCustomerOrdersWithLeftAndRightJoinAsync(
	CancellationToken cancellationToken)
{
	var customersWithOrders = _context.Customers
		.LeftJoin(
			_context.Orders,
			c => (int?)c.Id,
			o => o.CustomerId,
			(c, o) => new
			{
				CustomerId = (int?)c.Id,
				CustomerName = (string?)c.Name,
				OrderId = o != null ? (int?)o.Id : null,
				OrderDate = o != null ? (DateOnly?)o.OrderDate : null,
				Total = o != null ? (decimal?)o.Total : null
			});

	var ordersWithNoCustomer = _context.Customers
		.RightJoin(
			_context.Orders,
			c => (int?)c.Id,
			o => o.CustomerId,
			(c, o) => new { Customer = c, Order = o })
		.Where(x => x.Customer == null)
		.Select(x => new
		{
			CustomerId = (int?)null,
			CustomerName = (string?)null,
			OrderId = (int?)x.Order.Id,
			OrderDate = (DateOnly?)x.Order.OrderDate,
			Total = (decimal?)x.Order.Total
		});

	return await customersWithOrders
		.Concat(ordersWithNoCustomer)
		.Select(x => new GetCustomerOrderDto(x.CustomerId, x.CustomerName, x.OrderId, x.OrderDate, x.Total))
		.ToListAsync(cancellationToken);
}

The SQL uses a LEFT JOIN, followed by UNION ALL and a RIGHT JOIN.

SELECT [c].[Id] AS [CustomerId], [c].[Name] AS [CustomerName], [o].[Id] AS [OrderId], [o].[OrderDate], [o].[Total]
FROM [Customers] AS [c]
LEFT JOIN [Orders] AS [o] ON [c].[Id] = [o].[CustomerId]
UNION ALL
SELECT NULL AS [CustomerId], NULL AS [CustomerName], [o0].[Id] AS [OrderId], [o0].[OrderDate], [o0].[Total]
FROM [Customers] AS [c0]
RIGHT JOIN [Orders] AS [o0] ON [c0].[Id] = [o0].[CustomerId]
WHERE [c0].[Id] IS NULL

Using FullJoin in EF Core 11

EF Core 11 allows you to write true full join queries. It's written in a very similar way to how you use LeftJoin and RightJoin. You call FullJoin on the customers and pass in the orders.

// OrderRepository.cs
public async Task<IList<GetCustomerOrderDto>> GetCustomerOrdersAsync(
	CancellationToken cancellationToken) =>
		await _context.Customers
			.FullJoin(
				_context.Orders,
				c => (int?)c.Id,
				o => o.CustomerId,
				(c, o) => new GetCustomerOrderDto(
				   c!.Id,
				   c.Name,
				   o!.Id,
				   o.OrderDate,
				   o.TotalValue))
			.ToListAsync(cancellationToken);

When you look at the SQL, it no longer uses a left join and a right join. It uses a full join instead.

SELECT [c].[Id], [c].[Name], [o].[Id], [o].[OrderDate], [o].[Total]
	FROM [Customers] AS [c]
	FULL JOIN [Orders] AS [o] ON [c].[Id] = [o].[CustomerId]

MinBy and MaxBy support

The MinBy and MaxBy methods have been supported in LINQ since .NET 6. But they have never been supported in Entity Framework Core.

In this example, there are a number of blogs with posts. I want to get the blog with the fewest posts and the blog with the most posts. Before .NET 11, you had to write a workaround and more code to get a query like this to work.

EF Core 11 now supports MinBy and MaxBy, and it has also introduced the async methods, MinByAsync and MaxByAsync.

Using MinByAsync

To get the blog with the fewest posts, I call MinByAsync on the blogs and pass in the post count for each blog.

// BlogRepository.cs
public async Task<GetBlogDto?> GetBlogWithFewestPostsAsync(
	CancellationToken cancellationToken)
{
	var blog = await _context.Blogs
		.AsNoTracking()
		.MinByAsync(b => b.Posts.Count(), cancellationToken);

	return blog != null ? new GetBlogDto(blog.Id, blog.Name) : null;
}

Whichever blog has the fewest posts is returned.

The SQL gets the top blog and orders it by the number of posts in each blog.

SELECT TOP(1) [b].[Id], [b].[BlogTypeId], [b].[Name]
	FROM [Blogs] AS [b]
	ORDER BY (
		SELECT COUNT(*)
		FROM [Posts] AS [p]
		WHERE [b].[Id] = [p].[BlogId])

Using MaxByAsync

MaxByAsync works in exactly the same way. You just change the method name, and it returns the blog with the most posts.

// BlogRepository.cs
public async Task<GetBlogDto?> GetBlogWithMostPostsAsync(
	CancellationToken cancellationToken)
{
	var blog = await _context.Blogs
		.AsNoTracking()
		.MaxByAsync(b => b.Posts.Count(), cancellationToken);

	return blog != null ? new GetBlogDto(blog.Id, blog.Name) : null;
}

The only difference in the SQL is that the posts are ordered in descending order.

SELECT TOP(1) [b].[Id], [b].[BlogTypeId], [b].[Name]
	FROM [Blogs] AS [b]
	ORDER BY (
		SELECT COUNT(*)
		FROM [Posts] AS [p]
		WHERE [b].[Id] = [p].[BlogId]) DESC

GroupBy queries that can now be translated

When I've used GroupBy in Entity Framework Core, I would often get an error saying that the query could not be translated. As a result, I've always been a little nervous about using it.

In this query, I'm grouping the posts by the blog ID and selecting the most viewed post in each blog. I'm then composing over that top result to get the blog name and the author name.

// BlogRepository.cs
public async Task<IList<GetBlogTopPostDto>> GetTopPostPerBlogAsync(
	CancellationToken cancellationToken) =>
		await _context.Posts
			.GroupBy(p => p.BlogId)
			.Select(g => g.MaxBy(p => p.Views)!)
			.Select(p => new GetBlogTopPostDto(
				p.BlogId, p.Blog.Name, p.Title, p.Views, p.Author.Name)) // Composing over the top result
			.ToListAsync(cancellationToken);

The error in .NET 10

When I run the query in a .NET 10 project, I get a very lengthy error. Essentially, it says that the query could not be translated.

InvalidOperationException: The LINQ expression 'g .AsQueryable() .AsQueryable() .MaxBy(p => p.Views)' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'.

It's this sort of error that puts me off using GroupBy in Entity Framework Core.

The SQL in .NET 11

When I run the exact same query in a .NET 11 project, it works. It returns each blog with its most viewed post, the number of views and the author.

However, the SQL is very long and complicated.

SELECT [p4].[BlogId], [b].[Name], [p4].[Title], [p4].[Views], [a].[Name]
      FROM (
          SELECT [p].[BlogId]
          FROM [Posts] AS [p]
          GROUP BY [p].[BlogId]
      ) AS [p2]
      INNER JOIN [Blogs] AS [b] ON (
          SELECT TOP(1) [p1].[BlogId]
          FROM [Posts] AS [p1]
          WHERE [p2].[BlogId] = [p1].[BlogId]
          ORDER BY [p1].[Views] DESC) = [b].[Id]
      LEFT JOIN (
          SELECT [p3].[AuthorId], [p3].[BlogId], [p3].[Title], [p3].[Views]
          FROM (
              SELECT [p0].[AuthorId], [p0].[BlogId], [p0].[Title], [p0].[Views], ROW_NUMBER() OVER(PARTITION BY [p0].[BlogId] ORDER BY [p0].[Views] DESC) AS [row]
              FROM [Posts] AS [p0]
          ) AS [p3]
          WHERE [p3].[row] <= 1
      ) AS [p4] ON [p2].[BlogId] = [p4].[BlogId]
      INNER JOIN [Authors] AS [a] ON [p4].[AuthorId] = [a].[Id]

If you have a lot of records, I would use this with caution as you might get performance issues. Personally, I would stay well away from GroupBy unless I knew there wasn't a lot of data.

Better SQL for split queries

A split query writes separate queries for each join. This can get around some of the performance issues that come with joins, but of course, you are adding extra queries.

In this example, I'm running a split query that includes the navigation properties for the blog type and the posts.

// BlogRepository.cs
public async Task<IList<GetBlogWithPostsDto>> GetBlogsWithPostsAsync(
	CancellationToken cancellationToken)
{
	var blogs = await _context.Blogs
		.AsNoTracking()
		.Include(b => b.BlogType)
		.Include(b => b.Posts)
		.AsSplitQuery()
		.ToListAsync(cancellationToken);

	return blogs
		.Select(b => new GetBlogWithPostsDto(
			b.Id,
			b.Name,
			b.BlogType.Name,
			b.Posts.Select(p => new GetPostDto(p.Id, p.Title, p.Views)).ToList()))
		.ToList();
}

In .NET 10, this was made worse. The first Include is for the blog types, so the first query joins against the BlogTypes table. But the second query, which gets the posts, also joins on the BlogTypes table.

SELECT [b].[Id], [b].[BlogTypeId], [b].[Name], [b0].[Id], [b0].[Name]
	FROM [Blogs] AS [b]
	INNER JOIN [BlogTypes] AS [b0] ON [b].[BlogTypeId] = [b0].[Id]
	ORDER BY [b].[Id], [b0].[Id]
SELECT [p].[Id], [p].[AuthorId], [p].[BlogId], [p].[Title], [p].[Views], [b].[Id], [b0].[Id]
	FROM [Blogs] AS [b]
	INNER JOIN [BlogTypes] AS [b0] ON [b].[BlogTypeId] = [b0].[Id] /* Not needed */
	INNER JOIN [Posts] AS [p] ON [b].[Id] = [p].[BlogId]
	ORDER BY [b].[Id], [b0].[Id]

That join isn't needed for the second query. The relationship is between the blogs and the posts, and it has nothing to do with the blog types.

In .NET 11, there are still two queries. The first one still joins the blogs with the blog types, but the second query leaves out the blog types, so there is only a join between the blogs and the posts.

SELECT [b].[Id], [b].[BlogTypeId], [b].[Name], [b0].[Id], [b0].[Name]
	FROM [Blogs] AS [b]
	INNER JOIN [BlogTypes] AS [b0] ON [b].[BlogTypeId] = [b0].[Id]
	ORDER BY [b].[Id]
SELECT [p].[Id], [p].[AuthorId], [p].[BlogId], [p].[Title], [p].[Views], [b].[Id]
	FROM [Blogs] AS [b]
	INNER JOIN [Posts] AS [p] ON [b].[Id] = [p].[BlogId] /* No join on [BlogTypes] */
ORDER BY [b].[Id]

There is a GitHub issue that dates back to 2022 about the extra joins in split queries, so it has taken over four years to fix. With this fix, you can have a little more confidence in using split queries.

Create and apply EF Core migrations in one step

Migrations in Entity Framework Core allow you to automate changes to your database.

The two step approach

Normally, adding a migration is done in two steps. First, you make the change in your code and run the Add-Migration command in the Package Manager Console. This creates a migration script, which allows you to review all the changes that are going to be applied to your database.

If you're happy with them, you run Update-Database. As long as your connection string is set up correctly, it will update your database.

Using the -Add parameter

EF Core 11 allows you to add the migration and update the database with one command. You call Update-Database, add the -Migration parameter with the name of your migration, and add the -Add parameter.

Update-Database -Migration NewEntities -Add

If you use the .NET CLI, you can do the same with the --add option.

dotnet ef database update NewEntities --add

The migration is compiled at runtime. This helps with scenarios such as .NET Aspire and containers, where you can't stop and rebuild the application.

But this is a risky one for me. You are making a change to your database without checking the migration script, and hoping that it will be applied successfully.

It fails after the first migration

I also found an issue when making database changes after the first migration. I made a change in the Order entity where I renamed the Total property to TotalValue. Then I attempted to add the migration and update the database in one step.

Update-Database -Migration RenameOrderTotal -Add

A lot of errors were returned. When I looked at the migration script, rather than renaming just that column, it was creating all the tables again. This fails when it's run against the database because the tables already exist in the database.

It looks like this feature isn't working properly. To get around it, I had to go back to the two step approach and add the migration first.

Add-Migration RenameOrderTotal

Then I updated the database.

Update-Database

With the .NET CLI, the commands are dotnet ef migrations add followed by dotnet ef database update.

dotnet ef migrations add RenameOrderTotal
dotnet ef database update

Watch the video

Watch the video where I go through the new features in EF Core 11, including FullJoin, MinBy and MaxBy, GroupBy and split queries, and show you why creating and applying a migration in one step failed for me.