EF. How to join tables, sort rows and get higher entities?

I want to combine records from 2 tables, sort them and read TOP rows from a result set.

T1
--------
Id, Timestamp, Text1

T2
--------
Id, Timestamp, Text2

With SQL, this can be done as follows:

SELECT TOP 10 * FROM
(
    SELECT 
        [Timestamp], 
        [Text1] 

    FROM 
        T1

    UNION

    SELECT 
        [Timestamp], 
        [Text2]

    FROM 
        T2
) as x

ORDER BY [Timestamp]

Q: How can I accomplish this task with EF linq?

+3
source share
2 answers

To perform the operation, Unionyou need an anonymous type with the same names and property types:

var t1List = from a in allT1
        select new
        {
            TimeStamp = a.TimeStamp,
            Text = a.Text1
        };
var t2List = from b in allT2
        select new
        {
            TimeStamp = b.TimeStamp,
            Text = b.Text2
        };

var result = t1List.Union(t2List).OrderBy(ab => ab.TimeStamp).Take(10);
+7
source

How about something like:

var top10 = EFentity.t2.Union(EFentity.t1.ToList()).OrderBy(t=>t.Timestamp).ToList().Take(10);
0
source

All Articles