I am using Application Insights on my C# MVC web application. Going into End-to-end transaction details for a long running query.. I am getting that the following query runs over 10 times in a row on a slow page.
SELECT
[Extent1].[ID] AS [ID],
[Extent1].[paid] AS [paid]
FROM (SELECT
[TableXX].[ID] AS [ID],
[TableXX].[paid] AS [paid]
FROM [dbo].[TableXX] AS [TableXX]) AS [Extent1]
WHERE [Extent1].[ID] = @EntityKeyValue1
I'm not sure how to find it in my application. But also, I don't know why my TableXX is being subqueried with no where clause for the two fields if that makes sense.
Has anyone run into something like this? Could this be due to incorrectly using .Include, or just how EF structures certain type of Linq code smells?
Could this be it?
db.TableParent.Where(li => li.itemID == 16 && li.TableChild.TableXX != null && li.TableChild.companyId == company.id).ToList();
UPDATE:
So I used Database.Log and breakpoints to run my website locally and find the query that is causing the issue.
I create the following and pass it to a function that runs the second query below. Why is the ToList on the first one still letting the second one load them one by one?
List<TableParentItem> currentTableParentItems = db.TableParent.Where(i => i.id == givenId).Include(i => i.TableChild).Include(i => i.TableXX).GroupBy(i => new { i.id1, i.id2}).SelectMany(location => location.OrderByDescending(i => i.order).Take(1)).OrderBy(i => i.StartDate).ThenByDescending(i => i.id2).ToList();
..
result = currentTableParentItems.Where(i => i.Remaining > 0 && i.dueDate <= DateTime.Now).ToList();
Where i.Remaining is a get { return TableXX.remaining; }
.. I'm also confused because when I set a breakpoint before and after the currentTableParentItems var above.. I get multiple queries: 1 into TableXX, 1 into TableParent, and 2 into TableChild... and then 5th one for a random table not referenced on that line..