Reputation: 1305
I try to generate UNION
query in LINQ:
var a = _aReposytory.GetAll().OrderByDescending(t => t.EndT).Take(100);
var b = _bReposytory.GetAll().OrderByDescending(t => t.EndT).Take(100);
var c = _cReposytory.GetAll().OrderByDescending(t => t.EndT).Take(100);
var d = _dReposytory.GetAll().OrderByDescending(t => t.EndT).Take(100);
var result = a.Cast<IEntity>().Union(b.Cast<IEntity>())
.Union(c.Cast<IEntity>()).Union(d.Cast<IEntity>()).ToList();
All entityes inherit IEntity
interface and has same fields. _aReposytory.GetAll()
, _bReposytory.GetAll()
etc return IQueryable<T>
. But i get error when trying get result.
The specified LINQ expression contains references to queries that are associated with different contexts.
It is works when i using folowing UNION
logic. But it is four queries execution.
var union = new List<ICdcEntity>(a);
union.AddRange(b);
union.AddRange(c);
union.AddRange(d);
How generate single UNION
query in LINQ?
Upvotes: 0
Views: 1248
Reputation: 30464
If you are using Entity Framework (or something similar) to fetch data from a database, you can choose to let your database perform the query, and return only the data you want, or you can choose to fetch more data than you want in your end result and filter it in local memory.
The first is done AsQueryable
, the latter is done AsEnumerable
.
Although Queryable.Union exists, it can only unite tables that are in the same database.
You are performing the query on different repositories, this means that potentially their data might be in different databases.
If you want' to perform your union this way, you'll have to do it in local memory. Enumerable.AsEnumerable will bring your data to local memory, where it can be united with other data that is in local memory.
However, if your data is really supposed to be in the same database, then it would be much more efficient if you could perform your query AsQueryable. You should make certain that your repositories use the same instance of DbContext
. In that case you should be able to perform your queries on database sid.
By the way, if you are doing this kine of uniting often, consider putting this into one unit-of-work using the unit-of-work pattern.
More information: Implementing the repository pattern and unit-of-work patterns
Upvotes: 1
Reputation: 1
Can you create a unified class and populate all the attributes in the select clause in each query and then do a Union.
Upvotes: 0