Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 239
vborutenko Avatar asked Mar 18 '23 14:03

vborutenko


1 Answers

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:

  • MSDN documentation for the Queryable class in .NET 4.5. This documents all of the extension methods that can potentially be evaluated in the database instead of in the CLR.

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.

like image 157
cdhowie Avatar answered Mar 21 '23 07:03

cdhowie