user887983
user887983

Reputation:

Strange lambda Expression breaks down IIS

I do a query with an IQueryable<T> on an Entity.DbSet. When I insert this line of code:

query = 
     query.Where(x => x.VersionInt == query.Max(y => y.VersionInt))

The whole IIS breaks down when I compile and run with this line. If I remove it everything is allright. What's happening?

Upvotes: 0

Views: 176

Answers (2)

Olivier
Olivier

Reputation: 5698

Stack overflow exception (which will make the process crash - you cannot catch a StackOverflowException)!

Linq is lazy evaluated. Thus, your query is querying itself.

Did you meant

var querycopy = query;
query = query.Where(x => x.VersionInt == querycopy.Max(y => y.VersionInt))

or as oerkelens suggested, putting the "Max" evaluation outside of the Where would be even more performant.

Upvotes: 2

oerkelens
oerkelens

Reputation: 5151

Simply find the max(VersionInt) first before querying

var maxVersion = query.Max(x => x.VersionInt);
query = query.Where(x => x.VersionInt == maxVersion);

Upvotes: 2

Related Questions