Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I do a Union all in Entity Framework LINQ To Entities?

I came across a scenario where I had to use Union all, how can I achieve so in LINQ to entities ?

like image 970
Rami Sakr Avatar asked Mar 22 '12 18:03

Rami Sakr


People also ask

How do you write a Union query in LINQ?

LINQ Union operator is used for finding unique elements between two sequences (Collections). For example, suppose we have two collections A = { 1, 2, 3 }, and B = { 3, 4, 5 }. Union operator will find unique elements in both sequences. { 3 } element is available in both sequences.

What is Union in LINQ?

LINQ Union is an extension method that requires two collections to combine the two collections and returns the distinct elements from both collections. LINQ Union supports only method syntax; it does not support the query syntax. The Union method presents in both the classes Queryable class and Enumerable class.

Which is correct about LINQ to Entities?

LINQ to Entities provides Language-Integrated Query (LINQ) support that enables developers to write queries against the Entity Framework conceptual model using Visual Basic or Visual C#. Queries against the Entity Framework are represented by command tree queries, which execute against the object context.


2 Answers

Here is the answer you are looking for. Use the Concat keyword.

From the example:

var query = (from x in db.Table1 select new {A = x.A, B = x.B})     .Concat( from y in db.Table2 select new {A = y.A, B = y.B} ); 
like image 91
Justin Pihony Avatar answered Sep 21 '22 09:09

Justin Pihony


I believe Concat is what you're looking for.

var allResults = resultSet1.Concat(resultSet2); 

Obviously, both result sets must use the same type. And I believe there my be other requirements about how the result sets are constructed in the first place, but I don't know all the details.

like image 30
StriplingWarrior Avatar answered Sep 23 '22 09:09

StriplingWarrior