LINQ Join表然后groupby主表

时间:2010-06-25 18:34:59

标签: c# asp.net linq-to-sql

我正在尝试输出IDNums + Name + Max(TimeOut-TimeIn)表。我只想要每个ID的最大时间更改值,因为每个ID有多个时间条目。到目前为止,我有这个。但是,与ID关联的名称位于单独的表中。这是我试过的:

from IO_Time in db.IO_Times
join NameTable in db.NamesTable on IO_Time.IDNum equals NameTable.IDNum
orderby SqlMethods.DateDiffMinute(IO_Time.TimeIn, IO_Time.TimeOut) descending
group IO_Time by IO_Time.IDNum into list
select new
{
  ID = list.Key,
  Name = NameTable.Name
  Time = list.Max(t=> t.TimeOut-t.TimeIn)

});

但是,当然,NameTable.Name在该上下文中不存在。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

认为这应该有效...基本上它正在改变组密钥以包含名称......考虑到你已经拥有的连接,这应该没问题。

from IO_Time in db.IO_Times
join NameTable in db.NamesTable on IO_Time.IDNum equals NameTable.IDNum
orderby SqlMethods.DateDiffMinute(IO_Time.TimeIn, IO_Time.TimeOut) descending
group IO_Time by new { IO_Time.IDNum, NameTable.Name } into list
select new
{
  ID = list.Key.IDNum,
  Name = list.Key.Name
  Time = list.Max(t=> t.TimeOut-t.TimeIn)    
});