如何将此sql查询更改为linq?我有三个连接,最后一个连接是选择查询。
select mod.ModSerial,
met.MetSerial,
met.WaterNo,
met.PowerNo,
Gro.GroupDate
from MetlDB.dbo.tblMet AS met
join MetDB.dbo.tblMod AS mod on mod.ModID= met.ModID_FK
join MetDB.dbo.tblGroupData As Gro on Gro.MetID_FK= met.MetID
join(select MetID_FK,
max(GroupDataID) as maxgroupdata
from MetDB.dbo.tblGroupData
group by MetID_FK) g on met.MetID=g.MetID_FK and Gro.GroupDataID=g.maxgroupdata
答案 0 :(得分:1)
你走得很漂亮:
using (MetDBEntities ctnx = new MetDBEntities())
{
var query1 = from grp in ctnx.tblGroupDatas
group grp by grp.MetID_FK into g
let maxId = g.Max(gId => gId.GroupDataID)
select new { metId = g.Key, maxId };
var query2 = from met in ctnx.tblMets
from mod in ctnx.tblMods.Where(mo => mo.ModId == met.ModId_fk)
from grp in ctnx.tblGroupDatas.Where(gr => gr.MetID_FK == met.MetId)
from q1 in query1.Where(q => q.metId == met.MetId && grp.GroupDataID == q.maxId)
select new { mod.ModSerial, met.MetSerial, met.Waterno, met.powerno, grp.GroupDate };
var result = query2.ToList();
}
修改强> 我基于这个评论修改了我的答案:
这种方法会导致更大的数据集出现问题,因为你 从中获取tblMets和tblMods以及tblGroupDatas的每条记录 数据库进入内存......