Matt
Matt

Reputation: 26971

Manipulating entity framework to eliminate round trips to the database

Let's say I have the following bit of code (which I know could be easily modified to perform better, but it illustrates what I want to do)

List<Query> l = new List<Query>; 
// Query is a class that doesn't exist, it represents an EF operation

foreach (var x in Xs)
{
  Query o = { context.someEntity.Where(s=>s.Id==x.Id).First();} 
  // It wouldn't execute it, this is pseudo code for delegate/anonymous function
  l.Add(o)
}

Then send this list of Query to EF, and have it optimize so that it does the least amount of round trips possible. Let's call it BatchOptimizeAndRun; you would say

var results = BatchOptimizeAndRun(l);

And knowing what it knows from the schema it would reduce the overall query to an optimal version and execute that and place the read results in an array.

I hope I've described what I'm looking for accurately and more importantly that it exists. And if I sound like a rambling mad man, let's pretend this question never existed.

Upvotes: 0

Views: 669

Answers (1)

Nick
Nick

Reputation: 216

I'd have to echo Mr. Moore's advice, as I too have spent far too long constructing a linq-to-entities query of monolithic proportions only to find that I could have made a stored procedure in less time that was easier to read and faster to execute. That being said in your example...

List<int> ids = Xs.Select(x => x.Id).ToList();
var results = context.someEntity.Where(s => ids.Contains(s.Id)).ToList();

I believe this will compile to something like

SELECT
    *
FROM
    someEntity
WHERE
    Id IN (ids) --Where ids is a comma separated list of INT

Which will provide you with what you need.

Upvotes: 2

Related Questions