Skip to content

Query: optimize queries projecting correlated collections, so that they don't result in N+1 database queries #9282

Closed

Description

@maumar

In #8584 we allowed include pipeline to be reused for queries that project collection navigations as long as they are not composed on. This results in generating much better queries for those cases - no longer producing N+1 queries.

This could be further enhanced to support collection navigations that are composed on (e.g. customers.Select(c => c.Orders.Where(o => o.City == "London")), so that those queries also stop producing N+1 queries.

Activity

  1. added this to the Backlog milestone on Jul 27, 2017
  2. modified the milestones: Backlog, 2.1.0 on Aug 11, 2017
  3. sir-boformer commented on Oct 31, 2017

    @sir-boformer

    This feature is quite important for complex DTO/ViewModel generation. Here is a simple example

    public class ChatInfo
    {
    	public long Id { get; set; }
    
    	public string Title { get; set; }
    
    	public List<ChatEntry> Entries { get; set; } = new List<ChatEntry>();
    	public List<ChatAssignment> Assignments { get; set; } = new List<ChatAssignment>();
    }
    
    public class ChatEntry
    {
    	public long Id { get; set; }
    
    	public ChatInfo Chat { get; set; }
    
    	public string UserId { get; set; }
    	public string Message { get; set; }
    	public DateTime Time { get; set; }
    }
    
    public class ChatAssignment
    {
    	public long Id { get; set; }
    
    	public ChatInfo Chat { get; set; }
    
    	public string UserId { get; set; }
    }

    A common view model for a list of chat items:

    public class ChatListDto
    {
    	public string Title { get; set; }
    
    	public List<string> AssignedUserIds { get; set; }
    	public string LatestEntry { get; set; }
    }
    
    public class ChatEntryDto
    {
    	public string UserId { get; set; }
    	public string Message { get; set; }
    	public DateTime Time { get; set; }
    }

    A typical query to retrieve a list of chat list view models:

    await _context.Chats
    	.Include(c => c.Assignments)
    	.Where(c => c.Assignments.Any(a => a.UserId == "Steinmeier"))
    	.Select(c => new ChatListDto
    	{
    		Title = c.Title,
    
    		AssignedUserIds = c.Assignments.Select(a => a.UserId).ToList(),
    		LatestEntry = c.Entries
    			.OrderByDescending(e => e.Time)
    			.Select(e => new ChatEntryDto {
    				UserId = e.UserId,
    				Message = e.Message,
    				Time = e.Time
    			})
    			.FirstOrDefault()
    	})
       .ToListAsync();

    This generates n+1 queries (2 for each list item):

    Microsoft.EntityFrameworkCore.Database.Command:Information: Executed DbCommand (4ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
    SELECT [c].[Title], [c].[Id]
    FROM [Chats] AS [c]
    WHERE EXISTS (
        SELECT 1
        FROM [ChatAssignments] AS [a]
        WHERE ([a].[UserId] = N'Steinmeier') AND ([c].[Id] = [a].[ChatId]))
    
    Microsoft.EntityFrameworkCore.Database.Command:Information: Executed DbCommand (23ms) [Parameters=[@_outer_Id='?'], CommandType='Text', CommandTimeout='30']
    SELECT [a0].[UserId]
    FROM [ChatAssignments] AS [a0]
    WHERE @_outer_Id = [a0].[ChatId]
    
    Microsoft.EntityFrameworkCore.Database.Command:Information: Executed DbCommand (3ms) [Parameters=[@_outer_Id1='?'], CommandType='Text', CommandTimeout='30']
    SELECT TOP(1) [e].[UserId], [e].[Message], [e].[Time]
    FROM [ChatEntries] AS [e]
    WHERE @_outer_Id1 = [e].[ChatId]
    ORDER BY [e].[Time] DESC
    
    Microsoft.EntityFrameworkCore.Database.Command:Information: Executed DbCommand (0ms) [Parameters=[@_outer_Id='?'], CommandType='Text', CommandTimeout='30']
    SELECT [a0].[UserId]
    FROM [ChatAssignments] AS [a0]
    WHERE @_outer_Id = [a0].[ChatId]
    
    Microsoft.EntityFrameworkCore.Database.Command:Information: Executed DbCommand (0ms) [Parameters=[@_outer_Id1='?'], CommandType='Text', CommandTimeout='30']
    SELECT TOP(1) [e].[UserId], [e].[Message], [e].[Time]
    FROM [ChatEntries] AS [e]
    WHERE @_outer_Id1 = [e].[ChatId]
    ORDER BY [e].[Time] DESC
    
    Microsoft.EntityFrameworkCore.Database.Command:Information: Executed DbCommand (0ms) [Parameters=[@_outer_Id='?'], CommandType='Text', CommandTimeout='30']
    SELECT [a0].[UserId]
    FROM [ChatAssignments] AS [a0]
    WHERE @_outer_Id = [a0].[ChatId]
    
    Microsoft.EntityFrameworkCore.Database.Command:Information: Executed DbCommand (0ms) [Parameters=[@_outer_Id1='?'], CommandType='Text', CommandTimeout='30']
    SELECT TOP(1) [e].[UserId], [e].[Message], [e].[Time]
    FROM [ChatEntries] AS [e]
    WHERE @_outer_Id1 = [e].[ChatId]
    ORDER BY [e].[Time] DESC
    
    EFPlayground.Controllers.HomeController:Debug: [[ SPD-Chat - UserId: Schulz, Message: Geh sterben!]]
    EFPlayground.Controllers.HomeController:Debug: [[ Ausland-Chat - UserId: Trump, Message: MAGA <3 Putin]]
    EFPlayground.Controllers.HomeController:Debug: [[ Führer-Chat - UserId: Steinmeier, Message: Hey Mutti!]]
    
  4. jemiller0 commented on Nov 6, 2017

    @jemiller0

    I think I'm running into the same problem with the following projection query. The one-to-manys/collections are causing N+1 queries to occur. This is different than the behavior in Entity Framework 6 which creates nested JOINs and no N+1 queries. This is a use case that is important for a reporting application that I have. I have been wanting to switch to Entity Framework Core for everything, but, have run into issues like this. I think this is one of the last remaining issues that I have.

    var q = from oi in libraryContext.OrderItems
            select new
            {
                oi.Id,
                Order = oi.Order.Id,
                oi.OrderId,
                oi.Order.CreationTime,
                OrderStatus = oi.Order.OrderStatus.Name,
                oi.Order.OrderStatusId,
                OrderType = oi.Order.OrderType.Name,
                oi.Order.OrderTypeId,
                ReceiptStatus = oi.Holding.ReceiptStatus.Name,
                oi.Holding.ReceiptStatusId,
                Vendor = oi.Order.Vendor.Name,
                oi.Order.Vendor.EmailAddress,
                oi.Order.VendorId,
                Accounts = oi.OrderItemAccounts.Select(oia => oia.Account.Code),
                Donors = oi.OrderItemDonors.Select(oid => oid.Donor.Code),
                oi.VendorNotes,
                oi.SpecialNotes,
                oi.MiscellaneousNotes,
                oi.SelectorNotes,
                oi.Order.VendorCustomerId,
                DeliveryRoom = oi.Order.DeliveryRoom.Name,
                oi.Order.DeliveryRoomId,
                ExtendedCost = oi.UnitPrice * oi.Quantity,
                oi.VendorItemId,
                Bib = oi.Bib.Title,
                oi.BibId,
                oi.Bib.Author,
                oi.Bib.OclcNumber,
                OclcNumbers = oi.Bib.OclcNumbers.Select(n => n.Content),
                Isbns = oi.Bib.Isbns.Select(n => n.Content),
                Issns = oi.Bib.Issns.Select(n => n.Content),
                OtherNumbers = oi.Bib.Numbers.Where(n => n.Type == "024").Select(n => n.Content),
                PublisherNumbers = oi.Bib.Numbers.Where(n => n.Type == "028").Select(n => n.Content),
                Editions = oi.Bib.Editions.Select(n => n.Content),
                Publications = oi.Bib.Publications.Select(n => n.Content)
            };
    

    Does anyone know if this issue will be solved sometime soon?

  5. added a commit that references this issue on Dec 20, 2017
  6. added 3 commits that reference this issue on Jan 10, 2018
  7. changed the title [-]Query: improve include pipeline so it can be reused for queries projecting composed collection navigations (filters and projections)[/-] [+]Query: optimize queries projecting correlated collections, so that they don't result in N+1 database queries[/+] on Jan 10, 2018
  8. 20 remaining items

  9. maumar commented on Jan 24, 2018

    @maumar
    ContributorAuthor

    @jemiller0 I looked at the query you provided, and the problem is that adding filter after the projection makes it a much complicated query, from EF perspective - we create quite a complicated predicate, which gets client-evaluated and that disables correlated collection optimization and also this is why you don't see a WHERE clause in your query.

    You can modify the query slightly (move the filter before the projection):

    using (var lc = new LibraryContext())
                {
                    var q = from oi in lc.OrderItems
                            where oi.OrderItemAccounts.Select(oia => oia.Account.Code).Any(s => s == "XPUTT")
                            select new
                            {
                                oi.Id,
                                Order = oi.Order.Id,
                                oi.OrderId,
                                oi.Order.CreationTime,
                                OrderStatus = oi.Order.OrderStatus.Name,
                                oi.Order.OrderStatusId,
                                OrderType = oi.Order.OrderType.Name,
                                oi.Order.OrderTypeId,
                                ReceiptStatus = oi.Holding.ReceiptStatus.Name,
                                oi.Holding.ReceiptStatusId,
                                Vendor = oi.Order.Vendor.Name,
                                oi.Order.Vendor.EmailAddress,
                                oi.Order.VendorId,
                                Accounts = oi.OrderItemAccounts.Select(oia => oia.Account.Code).ToArray(),
                                Donors = oi.OrderItemDonors.Select(oid => oid.Donor.Code).ToArray(),
                                oi.VendorNotes,
                                oi.SpecialNotes,
                                oi.MiscellaneousNotes,
                                oi.SelectorNotes,
                                oi.Order.VendorCustomerId,
                                DeliveryRoom = oi.Order.DeliveryRoom.Name,
                                oi.Order.DeliveryRoomId,
                                ExtendedCost = oi.UnitPrice * oi.Quantity,
                                oi.VendorItemId,
                                Bib = oi.Bib.Title,
                                oi.BibId,
                                oi.Bib.Author,
                                oi.Bib.OclcNumber,
                                OclcNumbers = oi.Bib.OclcNumbers.Select(n => n.Content).ToArray(),
                                Isbns = oi.Bib.Isbns.Select(n => n.Content),
                                Issns = oi.Bib.Issns.Select(n => n.Content),
                                OtherNumbers = oi.Bib.Numbers.Where(n => n.Type == "024").Select(n => n.Content).ToArray(),
                                PublisherNumbers = oi.Bib.Numbers.Where(n => n.Type == "028").Select(n => n.Content).ToArray(),
                                Editions = oi.Bib.Editions.Select(n => n.Content).ToArray(),
                                Publications = oi.Bib.Publications.Select(n => n.Content).ToArray()
                            };
                    var l = q.Take(5).ToArray();
                    foreach (var oi in l) oi.Accounts.ToArray();
                }

    and you will get much better queries. (Disclaimer: I only tested it with a simplified model so there still might be more issues.)

  10. jemiller0 commented on Jan 24, 2018

    @jemiller0

    Thanks @maumar. I'm sorry I didn't get back to you yet. Some things came up a work and I haven't had a chance to test. The main reason I'm putting the filter at the bottom like that is that I'm using the query with a grid control (RadGrid) from a company called Telerik. The grid control allows you to enable filtering controls at the top of the grid and generates Dynamic LINQ filter strings. The output projection field names are what the grid knows. Otherwise, I agree, it would be best to do the filtering at the top.

  11. maumar commented on Jan 30, 2018

    @maumar
    ContributorAuthor

    filed #10811 to track the RadGrid issue, perhaps we can do some QM rewrite to improve the queries, making them take advantage of N+1 optimization (and others)

  12. Liero commented on Mar 19, 2018

    @Liero

    Hi, what about this query, which is still producing N+1 queries in EF2.1 preview:

    dbContext.ForumThreads.Include(t => t.Posts)
    .Select(t => new
    {
    t.Id,
    t.Title,
    PostAuhtors = t.Posts.Select(p => p.AuthorName).Take(5).ToArray()
    }).ToArray();

    https://stackoverflow.com/questions/49346001/how-to-avoid-n1-queries-in-ef-core-2-1/

  13. MaklaCof commented on Mar 19, 2018

    @MaklaCof

    I did not try this in 2.1, but I would like to mention another scenario (FirstOrDefault):

      context.Set<DbItem>()
        .Select(t => new {
          t.Id,
          t.Title,
          t.Detail.Where(t2 => t2.Lang == "ENG").Select(t2 => t2.Name).FirstOrDefault()
        }).ToList();
    
  14. ajcvickers commented on Mar 19, 2018

    @ajcvickers
    Contributor

    @Liero @MaklaCof Can you please file new issues including a runnable project/solution or complete code listing so that we can investigate what you are seeing. (This issue is closed, so it is unlikely that posting here will result in any action.)

  15. maumar commented on Mar 19, 2018

    @maumar
    ContributorAuthor

    @Liero this is a known limitation (there are other limitations that we are aware of, listed here: b95f23f)

    @MaklaCof this is already fixed by #10813

  16. modified the milestones: , 2.1.0 on Nov 11, 2019
  17. patcor commented on Nov 18, 2019

    @patcor

    var maps = ( from map in Set<Map>().Include(m => m.MapPoints) select new { Map = map, TotalCount = map.MapPoints.Count() } ) .OrderBy(m=>m.Map.Id) .Skip(0) .Take(10) .ToList();

    I have the code above. The table map has a one to many relation to MapPoints. So in this query I'm trying to list all maps and in the same query count the number of points from the MapPoints table.

    We are using EF core 2.2 and have problem with N+1.

    @maumar Is this supposed to be fixed in that version or is this specific issue that I have not fixed in 2.2?

  18. maumar commented on Nov 19, 2019

    @maumar
    ContributorAuthor

    @patcor 2.1 and 2.2 fix has a number of limitations, using Skip/Take is one of them. We have addressed them all in 3.0 which now produces a single query for all nested navigation/include scenarios

  19. added theissue type on Jun 15, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions