3

I'm planning on preparing some methods that returned me an already filtered collection of elements in a DB table, and then execute queries on those collections. I'm wondering if the first filtering will be executed as a separate statement or will it be joined.

e.g.

public IQueryable<Person> GetAlivePersons(){
    return db.Persons.Where(p => !p.IsDeceased);
}

public IQueryable<Person> GetElderPeople(){
    return GetAlivePersons().Where(p => p.Age > 75);
}

Will the second method hit the DB once or twice?

Thanks

willvv
  • 8,439
  • 16
  • 66
  • 101

1 Answers1

2

IQueryable is translated in sql only when you accessing result collection. That because your code hit DB once. This topic explains this point

Community
  • 1
  • 1
Sergey Vedernikov
  • 7,609
  • 2
  • 25
  • 27
  • It can be translated to SQL any time - you can just convert it to `ObejctQuery` and call `ToTraceString` and you will get SQL. But it follows the same rules for deffered execution as any other linq query. You must start to iterate collection or call methods like ToList or First to execute query. – Ladislav Mrnka Mar 01 '11 at 09:09
  • Well, that's some handy method (ToTraceString), I didn't know it existed. Thanks for that. – willvv Mar 03 '11 at 18:57