EF. How to union tables, sort rows, and get top entities?

匿名 (未验证) 提交于 2019-12-03 08:54:24

问题:

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

T1 -------- Id, Timestamp, Text1  T2 -------- Id, Timestamp, Text2 

With SQL it can be done this way:

SELECT TOP 10 * FROM (     SELECT          [Timestamp],          [Text1]       FROM          T1      UNION      SELECT          [Timestamp],          [Text2]      FROM          T2 ) as x  ORDER BY [Timestamp] 

Q: How can I do that task using EF linq?

回答1:

You need an anonymous type with the same property names and types before you can do an Union operation:

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); 


回答2:

How about something like:

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


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!