LINQ to SQL的:数据来自两个不相关的表,对日期进行排序 [英] LINQ to SQL: Data from two unrelated tables, sorting on date
问题描述
我有两个表 tblActionLog
和 tblLoginLog
。
这是 tblActionLog
:
tblActionLog
------------
ID (int)
Happened (DateTime)
...etc.
这是 tblLoginLog
:
tblLoginLog
-----------
ID (int)
LoginDate (DateTime)
...etc.
现在我想有一个 GridView控件
与这两个表中海誓山盟交错,使他们独立的日期信息进行排序的信息,例如:
Now I want to have a GridView
with information from both of these tables interleaved in eachother so that their separate date informations are sorted, e.g.:
LOG OF STUFF
-------------------------------
DATE | WHAT
2009-09-09 | Anderson logged in.
2009-09-08 | Smith made an action.
2009-09-08 | Smith logged in.
2009-09-06 | Anna made an action.
2009-09-04 | Smith made an action.
我希望这使得它很清楚。我想所有这些信息在一个单一的LINQ查询(不一定是一条SQL查询)。任何帮助AP preciated。
I hope this makes it clear enough. I want to get all of this information in a single LINQ query (not necessarily one SQL query). Any help appreciated.
推荐答案
您可能需要使用选择()和联盟()整理的结果。
You probably want to use Select() and Union() to collate the results.
var query = context.Logins.Where( l => l.UserID == userID )
.Select( l => new { Date = l.Date, What = "logged in" } )
.Union( context.Actions.Where( a => a.UserID == userID )
.Select( a => new { Date = a.Date, What = a.Action } ))
.OrderBy( r => r.Date );
注意:您可能需要兑现每个子查询(用了ToList()或AsEnumerable()),但我认为应该LINQ2SQL能够直接构建UNION。此外,这是完全未经测试 - 直接输入到答案编辑器,我没有检查工会法的签名,所以你可能需要调整
Note: you may need to materialize each subquery (use ToList() or AsEnumerable()), but I think LINQ2SQL should be able to construct the UNION directly. Also, this is completely untested - typed straight into the answer editor and I didn't check the signature of the Union method so you may need to adjust.
这篇关于LINQ to SQL的:数据来自两个不相关的表,对日期进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!