vborutenko
vborutenko

Reputation: 4443

Concat IQueryable collections in one db request

I use entity framework.I need concat two collections.For example:

IQueryable<SomeType> collection1 = context.Entiies.Where(predicate);
IQueryable<SomeType> collection2 = context.Entiies.Where(otherPredicate);

var result = collection1.concat(collection2).toList(); //1
var result = collection1.union(collection2).toList; //2

Both 1 and 2 variant will do 2 requests in database,because these methods need IEnumerable as parameter.So,the question is can I concat two Iqueryble collections with one database call

Upvotes: 4

Views: 6837

Answers (1)

cdhowie
cdhowie

Reputation: 169318

There are Concat() and Union() extension methods for IQueryable<T> in addition to IEnumerable<T>. You can use them on queryable objects. Union() maps to the SQL UNION operation and Concat() maps to UNION ALL.

As long as you don't convert the IQueryable<T> objects to IEnumerable<T> (either explicitly or implicitly) then you can just use these methods and they will be evaluated in the database if possible.

Further reading:


In glancing through the documentation I glossed over the detail that the extension methods declared on Queryable accept IQueryable<T> as the first parameter, but IEnumerable<T> as the second. As D Stanley points out, these methods will test if the argument is an IQueryable<T> and if so will attempt to resolve the operation using the relevant query engine.

Upvotes: 7

Related Questions