You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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?
varsql=$"SELECT b.* FROM FREETEXTTABLE(Books, Description, '{query}') as t JOIN Books as b ON t.[Key] = b.id";varbooks=_context.Books.FromSql(sql);books=books.Include(book =>book.Publisher).Include(book =>book.BookAuthors).ThenInclude(bookAuthor =>bookAuthor.Author).Include(book =>book.Cover).AsNoTracking();varpagedBooks=awaitPaginatedList<Book>.CreateAsync(books,currentPage??1,5);varmodel=newBookListViewModel(){PagedBooks=pagedBooks,Query=query};returnView(model);
I often get Timeout errors.
Please I need help. I can't upgrade to 2.1 at the moment
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()
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:
Retrieve books with one-to-one entities - query 2 (Includes with single entity)
Retrieve BookAuthors joined to Books with ids filter and put them to the lookup (ToLookup) based on book id - query 3
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.
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.
@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.
Activity
sdanyliv commentedon Jul 11, 2018
@Eilon, much better to show which queries are generated.
divega commentedon Jul 11, 2018
@smithaitufe could you provide a repro project and share how long this is taking and how long you expect it to take?
Eilon commentedon Jul 11, 2018
@sdanyliv not my issue, I just moved it from another repo 😄
smithaitufe commentedon Jul 17, 2018
This is the log generated.
I get the following in my browser
sdanyliv commentedon Jul 17, 2018
@smithaitufe if you need performance, you have to rewrite your query to reduce calls to
FREETEXTTABLEwhich 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).
Note, that previous implementation has SQL Injection issue -
$" '{query}'"Also i do not claim that this approach avoids eager loading issue.
smithaitufe commentedon Jul 17, 2018
@sdanyliv Thanks for your code suggestion.
Please is QueryAsync available in 2.0?
sdanyliv commentedon Jul 17, 2018
You have to install Dapper or execute command and read values itself. Better to do not invent wheels :)
smithaitufe commentedon Jul 17, 2018
@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?
sdanyliv commentedon Jul 18, 2018
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:
smitpatel commentedon Jul 18, 2018
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.
divega commentedon Jul 20, 2018
This may also help: improve-the-performance-of-full-text-queries.
sdanyliv commentedon Jul 20, 2018
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.
divega commentedon Jul 22, 2018
Assigning to myself to investigate a couple of ideas I have for a workaround.
29 remaining items
ajcvickers commentedon Nov 19, 2019
@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.