I have an example query with a Where Contains clause:
db.jobs.Where(Function(j) ids.Contains(j.id))
My issue is that the real world array is over 100 in length, the generated SQL takes each element as it's own parameter, so the WHERE clause is something like IN (@p1....@p100)
.
Sending over 100 parameters to the database is I guess slow, what would be a better approach of doing this query?
What is the maximum number of parameters that can be used before performance is reduced?
Is there a way to tell LINQ to send the array as 1 parameter rather than 100 parameters?
Here is my full modified query:
Dim totMins = db.jobs _
.Where(Function(j) ids.Contains(j.id)) _
.GroupBy(Function(wo) wo.id) _
.ToDictionary(Function(g) g.Key, Function(g) g.Sum(Function(wo) wo.DurationMin))
Before I had a forEach
loop and did over 100 database calls to get each total, so I thought this Dictionary approach would be better.
Edit
As mentioned in my comments, I was having an issue with the SQL excecuting multiple times (seemingly indefinatly)
I solved the issue by projecting into an anonymous object and calling ToArray
to execute the Linq instead.
Dim totMins = db.Jobs _
.Where(Function(j) ids.Contains(j.id)) _
.GroupBy(Function(j) j.id) _
.Select(Function(g) New With {g.Key, .Sum = g.Sum(Function(j) j.DurationMin)}) _
.ToArray() _
.ToDictionary(Function(g) g.Key, Function(g) g.Sum)
I can only assume that ToArray
and ToDictonary
handle the deferred execution of Linq-to-SQL differently, and for some reason ToDictonary
was performing multiple select queries
Also just to say that we are using Linq to SQL not EF, don't know if there is a difference with the provider – Luke T O'Brien Jun 27 '17 at 12:07