Skip to content

Multiple Include on FromSql is slow #12632

Closed
Closed

Description

@Eilon

From @smithaitufe on July 11, 2018 12:38

I am having a serious issue with ASPNET Core EF Queries.

They are very slow for me and it is worse when I include Include or ThenInclude in my code.

I am using version 2.0
Please what is the solution to this?

            var sql = $"SELECT b.* FROM FREETEXTTABLE(Books, Description, '{query}') as t JOIN    Books as b ON t.[Key] = b.id";
            var books = _context.Books.FromSql(sql);
            
            books = books
            .Include(book => book.Publisher)
            .Include(book => book.BookAuthors).ThenInclude(bookAuthor => bookAuthor.Author)
            .Include(book => book.Cover)
            .AsNoTracking();

            var pagedBooks = await PaginatedList<Book>.CreateAsync(books, currentPage ?? 1, 5);
            var model = new BookListViewModel() { PagedBooks = pagedBooks, Query = query };
            return View(model);

I often get Timeout errors.

Please I need help. I can't upgrade to 2.1 at the moment

Copied from original issue: dotnet/aspnetcore#3314

Activity

  1. sdanyliv commented on Jul 11, 2018

    @sdanyliv

    @Eilon, much better to show which queries are generated.

  2. divega commented on Jul 11, 2018

    @divega
    Contributor

    @smithaitufe could you provide a repro project and share how long this is taking and how long you expect it to take?

  3. Eilon commented on Jul 11, 2018

    @Eilon
    ContributorAuthor

    @sdanyliv not my issue, I just moved it from another repo 😄

  4. smithaitufe commented on Jul 17, 2018

    @smithaitufe

    This is the log generated.

          SELECT [b].[Id], [b].[CategoryId], [b].[CoverId], [b].[Description], [b].[GenreId], [b].[InsertedAt], [b].[NoInSeries], [b].[PublisherId], [b].[Series], [b].[SubTitle], [b].[Title], [b].[UpdatedAt], [b.Cover].[Id], [b.Cover].[Base64], [b.Cover].[ContentType], [b.Cover].[Extension], [b.Cover].[InsertedAt], [b.Cover].[Path], [b.Cover].[UpdatedAt], [b.Publisher].[Id], [b.Publisher].[CountryId], [b.Publisher].[InsertedAt], [b.Publisher].[Name], [b.Publisher].[PhoneNumber], [b.Publisher].[UpdatedAt]
          FROM (
              SELECT b.* FROM FREETEXTTABLE(Books, Description, 'Medicine') as t JOIN Books as b ON t.[Key] = b.id
          ) AS [b]
          LEFT JOIN [Images] AS [b.Cover] ON [b].[CoverId] = [b.Cover].[Id]
          INNER JOIN [Publishers] AS [b.Publisher] ON [b].[PublisherId] = [b.Publisher].[Id]
          ORDER BY [b].[Id]
          OFFSET @__p_1 ROWS FETCH NEXT @__p_2 ROWS ONLY
    Microsoft.EntityFrameworkCore.Database.Command:Information: Executed DbCommand (570ms) [Parameters=[@__p_1='?', @__p_2='?'], CommandType='Text', CommandTimeout='30']
    SELECT [b].[Id], [b].[CategoryId], [b].[CoverId], [b].[Description], [b].[GenreId], [b].[InsertedAt], [b].[NoInSeries], [b].[PublisherId], [b].[Series], [b].[SubTitle], [b].[Title], [b].[UpdatedAt], [b.Cover].[Id], [b.Cover].[Base64], [b.Cover].[ContentType], [b.Cover].[Extension], [b.Cover].[InsertedAt], [b.Cover].[Path], [b.Cover].[UpdatedAt], [b.Publisher].[Id], [b.Publisher].[CountryId], [b.Publisher].[InsertedAt], [b.Publisher].[Name], [b.Publisher].[PhoneNumber], [b.Publisher].[UpdatedAt]
    info: Microsoft.EntityFrameworkCore.Database.Command[20101]
          Executed DbCommand (570ms) [Parameters=[@__p_1='?', @__p_2='?'], CommandType='Text', CommandTimeout='30']
          SELECT [b].[Id], [b].[CategoryId], [b].[CoverId], [b].[Description], [b].[GenreId], [b].[InsertedAt], [b].[NoInSeries], [b].[PublisherId], [b].[Series], [b].[SubTitle], [b].[Title], [b].[UpdatedAt], [b.Cover].[Id], [b.Cover].[Base64], [b.Cover].[ContentType], [b.Cover].[Extension], [b.Cover].[InsertedAt], [b.Cover].[Path], [b.Cover].[UpdatedAt], [b.Publisher].[Id], [b.Publisher].[CountryId], [b.Publisher].[InsertedAt], [b.Publisher].[Name], [b.Publisher].[PhoneNumber], [b.Publisher].[UpdatedAt]
          FROM (
              SELECT b.* FROM FREETEXTTABLE(Books, Description, 'Medicine') as t JOIN Books as b ON t.[Key] = b.id
          ) AS [b]
          LEFT JOIN [Images] AS [b.Cover] ON [b].[CoverId] = [b.Cover].[Id]
          INNER JOIN [Publishers] AS [b.Publisher] ON [b].[PublisherId] = [b.Publisher].[Id]
          ORDER BY [b].[Id]
          OFFSET @__p_1 ROWS FETCH NEXT @__p_2 ROWS ONLY
    Microsoft.EntityFrameworkCore.Database.Command:Information: Executed DbCommand (570ms) [Parameters=[@__p_1='?', @__p_2='?'], CommandType='Text', CommandTimeout='30']
    SELECT [b].[Id], [b].[CategoryId], [b].[CoverId], [b].[Description], [b].[GenreId], [b].[InsertedAt], [b].[NoInSeries], [b].[PublisherId], [b].[Series], [b].[SubTitle], [b].[Title], [b].[UpdatedAt], [b.Cover].[Id], [b.Cover].[Base64], [b.Cover].[ContentType], [b.Cover].[Extension], [b.Cover].[InsertedAt], [b.Cover].[Path], [b.Cover].[UpdatedAt], [b.Publisher].[Id], [b.Publisher].[CountryId], [b.Publisher].[InsertedAt], [b.Publisher].[Name], [b.Publisher].[PhoneNumber], [b.Publisher].[UpdatedAt]
    FROM (
        SELECT b.* FROM FREETEXTTABLE(Books, Description, 'Medicine') as t JOIN Books as b ON t.[Key] = b.id
    ) AS [b]
    LEFT JOIN [Images] AS [b.Cover] ON [b].[CoverId] = [b.Cover].[Id]
    INNER JOIN [Publishers] AS [b.Publisher] ON [b].[PublisherId] = [b.Publisher].[Id]
    ORDER BY [b].[Id]
    OFFSET @__p_1 ROWS FETCH NEXT @__p_2 ROWS ONLY
    The thread 29274 has exited with code 0 (0x0).
    ...
    The thread 32497 has exited with code 0 (0x0).

    I get the following in my browser

    An unhandled exception occurred while processing the request.
    Win32Exception: Unknown error 258
    
    Unknown location
    SqlException: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
    
    System.Data.SqlClient.SqlConnection.OnError(SqlException exception, bool breakConnection, Action<Action> wrapCloseInAction)
    SqlException: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
    
        System.Data.SqlClient.SqlConnection.OnError(SqlException exception, bool breakConnection, Action<Action> wrapCloseInAction)
        System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, bool breakConnection, Action<Action> wrapCloseInAction)
        System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, bool callerHasConnectionLock, bool asyncClose)
        System.Data.SqlClient.TdsParserStateObject+<>c__DisplayClass173_0.<OnTimeout>b__0(Task _)
        System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
        System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
        Microsoft.EntityFrameworkCore.Query.Internal.AsyncQueryingEnumerable+AsyncEnumerator+<BufferAllAsync>d__15.MoveNext()
        System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
        System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
        Microsoft.EntityFrameworkCore.Storage.RelationalConnection+<Microsoft-EntityFrameworkCore-Storage-IRelationalConnection-RegisterBufferableAsync>d__45.MoveNext()
        System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
        System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
        Microsoft.EntityFrameworkCore.Query.Internal.AsyncQueryingEnumerable+AsyncEnumerator+<BufferlessMoveNext>d__10.MoveNext()
        System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
        System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
        Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerExecutionStrategy+<ExecuteAsync>d__7.MoveNext()
        System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
        System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
        System.Runtime.CompilerServices.TaskAwaiter.GetResult()
        Microsoft.EntityFrameworkCore.Query.Internal.AsyncQueryingEnumerable+AsyncEnumerator+<MoveNext>d__9.MoveNext()
        System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
        System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
        System.Runtime.CompilerServices.TaskAwaiter.GetResult()
    
  5. sdanyliv commented on Jul 17, 2018

    @sdanyliv

    @smithaitufe if you need performance, you have to rewrite your query to reduce calls to FREETEXTTABLE which should be slowest place in your query.

    At first run RAW query that returns only book ID's and apply pagination (Dapper is enough for running such queries).

    const int pageSize = 5;
    var offset = ((currentPage ?? 1) - 1) * pageSize;
    // collect ID's
    var ids = (await _context.Database.GetDbConnection().QueryAsync<int>(
    @"SELECT t.[Key] 
    FROM FREETEXTTABLE(Books, Description, @Query) as t
    ORDER BY t.[Key]
    OFFSET @Offset ROWS
      FETCH NEXT @PageSize ROWS ONLY
    ", new { Query = query, Offset = offset, PageSize = pageSize })).ToList();
    
    var pagedBooks = await _context.Books.AsNoTracking()
       .Include(book => book.Publisher)
       .Include(book => book.BookAuthors).ThenInclude(bookAuthor => bookAuthor.Author)
       .Include(book => book.Cover)
       .Where(book => ids.Contains(book.id))
       .ToListAsync();
    
    var model = new BookListViewModel() { PagedBooks = pagedBooks , Query = query };
    return View(model);

    Note, that previous implementation has SQL Injection issue - $" '{query}'"
    Also i do not claim that this approach avoids eager loading issue.

  6. smithaitufe commented on Jul 17, 2018

    @smithaitufe

    @sdanyliv Thanks for your code suggestion.
    Please is QueryAsync available in 2.0?

  7. sdanyliv commented on Jul 17, 2018

    @sdanyliv

    You have to install Dapper or execute command and read values itself. Better to do not invent wheels :)

  8. smithaitufe commented on Jul 17, 2018

    @smithaitufe

    @sdanyliv I am having the same experience after trying your suggestion. Thanks a lot though.

    I know the issue is the part with Eager Loading.

    What alternative exists?

    SqlException: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
    
        System.Data.SqlClient.SqlConnection.OnError(SqlException exception, bool breakConnection, Action<Action> wrapCloseInAction)
        System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, bool breakConnection, Action<Action> wrapCloseInAction)
        System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, bool callerHasConnectionLock, bool asyncClose)
        System.Data.SqlClient.TdsParserStateObject+<>c__DisplayClass173_0.<OnTimeout>b__0(Task _)
        System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
        System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
        Microsoft.EntityFrameworkCore.Query.Internal.AsyncQueryingEnumerable+AsyncEnumerator+<BufferAllAsync>d__15.MoveNext()
        System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
        System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
        Microsoft.EntityFrameworkCore.Storage.RelationalConnection+<Microsoft-EntityFrameworkCore-Storage-IRelationalConnection-RegisterBufferableAsync>d__45.MoveNext()
        System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
        System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
        Microsoft.EntityFrameworkCore.Query.Internal.AsyncQueryingEnumerable+AsyncEnumerator+<BufferlessMoveNext>d__10.MoveNext()
        System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
        System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
        Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerExecutionStrategy+<ExecuteAsync>d__7.MoveNext()
        System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
        System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
        System.Runtime.CompilerServices.TaskAwaiter.GetResult()
        Microsoft.EntityFrameworkCore.Query.Internal.AsyncQueryingEnumerable+AsyncEnumerator+<MoveNext>d__9.MoveNext()
        System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
        System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
        System.Runtime.CompilerServices.TaskAwaiter.GetResult()
        Microsoft.EntityFrameworkCore.Query.Internal.QueryBuffer+<IncludeCollectionAsync>d__12.MoveNext()
        System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
        System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
        Microsoft.EntityFrameworkCore.Query.Internal.IncludeCompiler+<_IncludeAsync>d__20.MoveNext()
        System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
        System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
        System.Runtime.CompilerServices.TaskAwaiter.GetResult()
        Microsoft.EntityFrameworkCore.Query.ExpressionVisitors.Internal.TaskLiftingExpressionVisitor+<_ExecuteAsync>d__8.MoveNext()
        System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
        System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
        Microsoft.EntityFrameworkCore.Query.EntityQueryModelVisitor+AsyncSelectEnumerable+AsyncSelectEnumerator+<MoveNext>d__3.MoveNext()
        System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
        System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
        System.Runtime.CompilerServices.TaskAwaiter.GetResult()
        Microsoft.EntityFrameworkCore.Query.Internal.AsyncLinqOperatorProvider+ExceptionInterceptor+EnumeratorExceptionInterceptor+<MoveNext>d__5.MoveNext()
        System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
        System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
        System.Runtime.CompilerServices.ConfiguredTaskAwaitable+ConfiguredTaskAwaiter.GetResult()
        System.Linq.AsyncEnumerable+<Aggregate_>d__6.MoveNext()
        System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
        System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
        System.Runtime.CompilerServices.TaskAwaiter.GetResult()
        Library.Search.Controllers.HomeController+<Search2>d__3.MoveNext() in HomeController.cs
    
                    var pagedBooks = await _context.Books.AsNoTracking()
    
    System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    System.Runtime.CompilerServices.TaskAwaiter.GetResult()
    Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker+<InvokeActionMethodAsync>d__12.MoveNext()
    System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker+<InvokeNextActionFilterAsync>d__10.MoveNext()
    System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext context)
    Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
    Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker+<InvokeInnerFilterAsync>d__14.MoveNext()
    System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker+<InvokeNextResourceFilter>d__22.MoveNext()
    System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
    Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
    Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker+<InvokeFilterPipelineAsync>d__17.MoveNext()
    System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker+<InvokeAsync>d__15.MoveNext()
    System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    Microsoft.AspNetCore.Builder.RouterMiddleware+<Invoke>d__4.MoveNext()
    System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware+<Invoke>d__7.MoveNext()
    
  9. sdanyliv commented on Jul 18, 2018

    @sdanyliv

    Unfortunately i can not help here because you are sending Database entities over internet without any DTO mappings and i don’t know how your model is defined.
    Eager Loading is simplifying retrieving details for master records which cause additional queries. Sometimes it is powerfull feature (when you need change tracker) but it has performance penalty as i shown before and you have to use it very carefully.

    Simple steps to emulate are:

    1. Retrieve books with one-to-one entities - query 2 (Includes with single entity)
    2. Retrieve BookAuthors joined to Books with ids filter and put them to the lookup (ToLookup) based on book id - query 3
    3. Add book authors to the book entities manually
  10. smitpatel commented on Jul 18, 2018

    @smitpatel
    Contributor

    I know the issue is the part with Eager Loading.

    Because you are doing a lot of joins in database with using FreeTextTable?
    I examined the Linq query and generate SQL for it. EF Core is generating optimal possible SQL for all cases. Since you are eager loading 3 different paths, EF core will do join in same query for 2 reference navigation and do a second query for the collection Include.
    The timeout you are receiving is from SqlClient side which means that the SQL is just taking long time to finish. If even after generating optimal SQL with all necessary join for eager loading, if the join is going to take long time on server (due to data or computation of FREETEXTTABLE) then all you got is to increase the command time out. Else run multiple queries to get data from server and EF Core will fix it up on client side.

  11. divega commented on Jul 20, 2018

    @divega
    Contributor
  12. sdanyliv commented on Jul 20, 2018

    @sdanyliv

    EF Core is generating optimal possible SQL for all cases

    IMHO, for almost all cases, best solution for Eager Loading is to create temporary table, insert master records and then fetch details using this prepared table. Not trivial and EF Core gives no ways for workaround.

  13. self-assigned this
    on Jul 22, 2018
  14. divega commented on Jul 22, 2018

    @divega
    Contributor

    Assigning to myself to investigate a couple of ideas I have for a workaround.

  15. 29 remaining items

  16. modified the milestone: Backlog on Nov 15, 2019
  17. ajcvickers commented on Nov 19, 2019

    @ajcvickers
    Contributor

    @smithaitufe We don't believe this is an issue any more due to the changes made to the query code in 3.0. If you are still able to reproduce, then please comment here or open a new issue and include a small, runnable project/solution or complete code listing so that we can investigate some more.

  18. added this to the 3.1.0 milestone on Nov 19, 2019
  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

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions