ChiefTwoPencils
ChiefTwoPencils

Reputation: 13940

Do linq queries re-execute if no changes occured?

I was reading up on LINQ. I know that there are deferred and immediate queries. I know with deferred types running the query when it's enumerated allows any changes to the data set to be reflected in each enumeration. But I can't seem to find an answer if there's a mechanism in place to prevent the query from running if no changes occurred to the data set since the last enumeration.

I read on MSDN referring to LINQ queries:

Therefore, it follows that if a query is enumerated twice it will be executed twice.

Have I overlooked an obvious - but...?

Upvotes: 2

Views: 246

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1063338

Indeed, there is none. Actually, that's not quite true - some LINQ providers will spot trivial but common examples like:

int id = ...
var customer = ctx.Customers.SingleOrDefault(x => x.Id == id);

and will intercept that via the identity-manager, i.e. it will check whether it has a matching record already in the context; if it does: it doesn't execute anything.

You should note that the re-execution also has nothing to do with whether or not data has changed; it will re-execute (or not) regardless.

There are two take-away messages here:

  • don't iterate any enumerable more than once: not least, it isn't guaranteed to work at all
  • if you want to buffer data, put it into a list/array

So:

var list = someQuery.ToList();

will never re-execute the query, no matter how many times you iterate over list. Because list is not a query: it is a list.

A third take-away would be:

  • if you have a context that lives long enough that it is interesting to ask about data migration, then you are probably holding your data-context for far, far too long - they are intended to be short-lived

Upvotes: 2

Related Questions