实体框架通过选择列加入组

问题描述 投票:0回答:1

我有 2 个表要通过 linq 查询连接

我想连接 2 个表,我想对多个列进行分组,但我想选择特定列并在某些适用的列上使用 datepart 等。我似乎能够毫无问题地选择列,但后来我在其中添加了一个分组,但它不起作用。

var data = from p in context.tablea 
join s in context.tableb
on new
{ p.id,
  p.name
}
equals
new
{
  s.id,
  s.name
}
 group p by new
{
 p.name
 p.type
 } into x
 Select new
 {
   p.columnA, p.columnB, s.columa, 
   s.date.value.Month
  }

它告诉我 p 或 s 在当前上下文中不存在。但如果我将组删除,我可以选择任何列。我看到的任何使用 group by 的示例似乎在 select new 中都有一个键,后跟一个总和或计数,但我想选择上面的列,有什么想法吗?谢谢

c# sql-server entity-framework linq group-by
1个回答
0
投票

您应该使用

group new { p, s }
将多个条目添加到组中,并在
select
语句中从组中获取第一个值。

var data = from p in context.tablea 
    join s in context.tableb 
        on new { p.id, p.name } equals new { s.id, s.name }
    group new { p, s } by new { p.name, p.type } into x
    select new
    {
        ColumnA = x.First(y => y.p.columnA), 
        ColumnB = x.First(y => y.p.columnB), 
        Columa = x.First(y => y.s.columa), 
        Month = x.First(y => y.s.date.value.Month)
    }
© www.soinside.com 2019 - 2024. All rights reserved.