Linq-to-sql加入了一对多

时间:2018-02-21 15:29:25

标签: linq-to-sql

这是我的Linq-to-sql查询:

var ds = (from f in dc.Fields
          from l in dc.Units.Where( ltu => ltu.TestID == f.Testid && ltu.tid == tid && ltu.Lbid != null).DefaultIfEmpty()
          from s in dc.Sites.Where( st => st.lbid == l.Lbid).DefaultIfEmpty()
          where f.tid == tid && f.tablename == e.Parameters[0].Value && f.tablename.Contains(tableprefix) 
          orderby f.fieldorder
          select new { ID = f.id, Units = "Units: " + l.Unit + "For Sites: " + s.siteid}

我如何更改代码,以便如果某个字段有多个单位和网站,则选择所有这些而不仅仅是第一个。

**Fields**
ID    |    Testid    |   fieldorder  |  tablename  |  tid
 0    |     test1    |      1        |    tbl1     |   100
 1    |     test2    |      2        |    tbl2     |   100

**Units**
ID    |    TestID   |  tid   |   Lbid   |  Unit
 0    |     test1   |  100   |   Lb1    |   m/s
 1    |     test1   |  100   |   Lb1    |   km/s

**Sites**
ID    |    siteid   |  lbid
 0    |     100     |   Lb1
 1    |     200     |   Lb1

所以我想得到的是:

  

ID = 0,单位="单位:" m / s,km / s"对于网站:" 100,200

1 个答案:

答案 0 :(得分:0)

我不确定您的查询是否返回了您期望的结果(我从中获取了四行),但是这里是通过Fields.ID组合行的修改:

var ds = from f in dc.Fields
         from l in dc.Units.Where(ltu => ltu.TestID == f.Testid && ltu.tid == tid && ltu.Lbid != null).DefaultIfEmpty()
         from s in dc.Sites.Where(st => st.lbid == l?.Lbid).DefaultIfEmpty()
         where f.tid == tid && f.tablename == e.Parameters[0].Value && f.tablename.Contains(tableprefix)
         group new { f, l, s } by f.ID into flsg
         orderby flsg.First().f.fieldorder
         select new { ID = flsg.Key, Units = "Units: " + String.Join(",", flsg.Select(fls => fls.l?.Unit)) + " For Sites: " + String.Join(",", flsg.Select(fls => fls.s?.siteid)) };