Skip to content

UseQuerySplittingBehavior.OnlyCollections #24420

Closed as duplicate
Closed as duplicate

Description

@rogerfar

I have some big queries with lots of includes which caused performance issues so we enabled "QuerySplittingBehavior.SplitQuery".

But for most cases it's not necessary to do the splitting, even better, not all parts of the query need to be split:

var users = _context
			.Users
			.Include(u => u.SuperVisor) // 1 to many relation, can use a regular join
			.Include(u => u.Subordinates) // many to many relation, should do a separate query
			.ToList();

Would it be an idea to add an option to UseQuerySplittingBehavior to only split the parts that are a N..N join?

Activity

  1. ajcvickers commented on Mar 23, 2021

    @ajcvickers
    Contributor

    @rogerfar Query splitting is useful whenever a collection is included, regardless of whether that collection is from a many-to-many relationship or a one-to-many relationship.

  2. rogerfar commented on Mar 23, 2021

    @rogerfar
    Author

    @ajcvickers it's not useful when it's a 1 to many at all.

    Or are you saying that this

    SELECT * FROM Users
    SELECT * FROM Manager
    

    is more effective than this

    SELECT
    	*
    FROM
    	Users
    LEFT JOIN
    	Managers ON Managers.ManagerId = Users.ManagerId
    
  3. roji commented on Mar 23, 2021

    @roji
    Member

    It most definitely is, if the LEFT JOIN duplicates a huge amount of Users fields because each User has many Managers.

  4. rogerfar commented on Mar 23, 2021

    @rogerfar
    Author

    No it doesn't have many managers, I'm specifically talking about 1 user has 1 manager (1..N correct?), not 1 user has many managers (N..M right?).

    Many managers have many users yes, so then it would be much better to have 2 separate queries, but if many users have 1 manager, it's better to have a join query correct?

    Maybe my terminology is incorrect, it's been a while :-)

    So if you have this condition: 1 user has 1 manager, but 1 user has many subordinates. Now it will split the query in multiple queries, but we can optimize this by splitting only the many to many join.

  5. roji commented on Mar 23, 2021

    @roji
    Member

    I'm specifically talking about 1 user has 1 manager (1..N correct?)

    Maybe it's 1..N viewed from the manager perspective, but from the user's perspective there's only one manager. That's called a "reference navigation" in EF Core, and these indeed don't generate split queries in EF Core. You should be seeing a simple LEFT JOIN for the Manager.

  6. rogerfar commented on Mar 23, 2021

    @rogerfar
    Author

    Also when QuerySplittingBehavior.SplitQuery is set? Because it looks like it's also splitting those.

  7. roji commented on Mar 23, 2021

    @roji
    Member

    See the complete code sample below, which shows the EF Core behavior.

    In this sample a single Blog has many Posts, each of which has many Comments. The query selects all Posts, including both Blogs and Comments - using AsSplitQuery. The resulting two queries are:

    info: Microsoft.EntityFrameworkCore.Database.Command[20101]
          Executed DbCommand (22ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
          SELECT [p].[Id], [p].[BlogId], [p].[Title], [b].[Id], [b].[Name]
          FROM [Posts] AS [p]
          LEFT JOIN [Blogs] AS [b] ON [p].[BlogId] = [b].[Id]
          ORDER BY [p].[Id], [b].[Id]
    info: Microsoft.EntityFrameworkCore.Database.Command[20101]
          Executed DbCommand (8ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
          SELECT [c].[Id], [c].[PostId], [c].[Text], [p].[Id], [b].[Id]
          FROM [Posts] AS [p]
          LEFT JOIN [Blogs] AS [b] ON [p].[BlogId] = [b].[Id]
          INNER JOIN [Comment] AS [c] ON [p].[Id] = [c].[PostId]

    The first query fetches all Posts, including their Blogs - that's precisely the reference navigation we discussed above (since each Post has just one Blog). However, since Comments are a collection navigation on each Post (one-to-many), it is split to a separate query which fetches only the Comment information.

    If you're seeing something different, please post a runnable code sample similar to the one below (you can try tweaking that to try to produce the behavior you want).

    Code sample
    await using (var ctx = new BlogContext())
    {
        await ctx.Database.EnsureDeletedAsync();
        await ctx.Database.EnsureCreatedAsync();
    
        ctx.Blogs.Add(new()
        {
            Name = "Blog1",
            Posts = new List<Post>
            {
                new()
                {
                    Title = "Post1",
                    Comments = new List<Comment>()
                    {
                        new() { Text = "Comment1" }
                    }
                }
            }
        });
    
        await ctx.SaveChangesAsync();
    }
    
    await using (var ctx = new BlogContext())
    {
        _ = await ctx.Posts
            .AsSplitQuery()
            .Include(p => p.Blog)
            .Include(p => p.Comments)
            .ToListAsync();
    }
    
    public class BlogContext : DbContext
    {
        public DbSet<Blog> Blogs { get; set; }
        public DbSet<Post> Posts { get; set; }
    
        static ILoggerFactory ContextLoggerFactory
            => LoggerFactory.Create(b => b.AddConsole().AddFilter("", LogLevel.Information));
    
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            => optionsBuilder
                .UseSqlServer(@"Server=localhost;Database=test;User=SA;Password=Abcd5678;Connect Timeout=60;ConnectRetryCount=0")
                .EnableSensitiveDataLogging()
                .UseLoggerFactory(ContextLoggerFactory);
    }
    
    public class Blog
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public List<Post> Posts { get; set; }
    }
    
    public class Post
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public Blog Blog { get; set; }
        public List<Comment> Comments { get; set; }
    }
    
    public class Comment
    {
        public int Id { get; set; }
        public string Text { get; set; }
        public Post Post { get; set; }
    }
  8. rogerfar commented on Mar 23, 2021

    @rogerfar
    Author

    Interesting, thanks for the detailed response, I will look deeper into my queries, if it already does this then consider this feature request as a dud.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions