Skary
Skary

Reputation: 1362

Execution of Any() clause against IQueryable object

I have an object IQueryable that represent some query over my db-model. Now i need to do some validation to that IQeryable and return back the object in that way

 private IQuerable<myTableType> ValidateQery ( IQuerable<myTableType> query , string user )
 {
           return query.Where ( x => db.tblUsers.Where( y => y.User == user && y.Privilege >= x.PrivilegeRequired).Any() )
 }

Now what i would like to understand is if the Any() clause is executed immidiatly or if it generate T-SQL that will be merged with previous. I ask that because i wuold avoid to execute a query against the db in that moment.

Edit : Thanks for the advice of 'using' clause, it was a fault that i made now (writing this code example) because i am not able to test code now (i have no visual studio on my machine in this moment) but my problem in general was about that situation.

Upvotes: 0

Views: 137

Answers (2)

Servy
Servy

Reputation: 203847

The Any is inside of a lambda in Queryable.Where, and as such is not executed as C# code and is instead translated into an Expression and passed to the query provider when the IQueryable returned from Where is iterated.

On a site node, you're disposing of the context before the IQueryable you return can ever be iterated, so it'll always fail when you do iterate it.

Upvotes: 6

Jon Skeet
Jon Skeet

Reputation: 1502376

It's part of the query - it's within a Where clause.

So no, it won't be executed immediately. Having said that, you appear to be closing the context that the query uses, so I suspect that by the time it is used, it'll be broken...

Upvotes: 3

Related Questions