简体   繁体   English

LINQ选择具有不同ForeignKeyId列的最新记录

[英]LINQ Select newest records that have distinct ForeignKeyId column

I have the following SQL query: 我有以下SQL查询:

SELECT 
   table1.Id AS EinAusgangId, 
   table1.Ausgabedatum, 
   table1.Rueckgabedatum, 
   table1.WerkzeugId, 
   cpmWerkzeug.Name
FROM cpmEinAusgang AS table1 
INNER JOIN cpmWerkzeug ON table1.WerkzeugId = cpmWerkzeug.Id
WHERE table1.Id = (SELECT MAX(Id) AS Expr1 
                   FROM dbo.cpmEinAusgang
                   WHERE table1.WerkzeugId = WerkzeugId)

My aim is to convert the whole query into a LINQ statement for further use in a .Net Application. 我的目标是将整个查询转换为LINQ语句,以便在.Net应用程序中进一步使用。 I already converted joined tables to LINQ but is it also possible to use a select in the where clause? 我已经将连接表转换为LINQ,但是也可以在where子句中使用select

This is what I got so far, which gives me almost the same result as the SQL statement above, but has major errors when the table cpmEinAusgang contains more then one record for one cpmWerkzeug 这是我到目前为止所得到的,它给出了与上面的SQL语句几乎相同的结果,但是当表cpmEinAusgang包含一个cpmWerkzeug多个记录时会出现重大错误

using (var dbContext = new cpmEntities())
{
  var werkzeuge = from w in dbContext.cpmWerkzeug
  join e in dbContext.cpmEinAusgang
  on w.Id equals e.WerkzeugId
  where e.Rueckgabedatum == null
  orderby w.Name
  select w;

  return werkzeuge.ToList();
}

Has anyone an idea how to achieve the above sql in linq? 有谁知道如何在linq中实现上述sql? Thanks for your help. 谢谢你的帮助。 :) :)

EDIT:solved (see below) 编辑:解决(见下文)

var werkzeugeImUmlauf = from w in dbContext.cpmWerkzeug
                                join e in dbContext.cpmEinAusgang
                                on w.Id equals e.WerkzeugId
                                where e.Id == dbContext.cpmEinAusgang.Where(x => x.WerkzeugId == e.WerkzeugId).Max(x => x.Id) select w;

This is the final solution. 这是最终的解决方案。 As mentioned by Mittal in his answer, it is possible to write a sub-query in LINQ. 正如Mittal在他的回答中所提到的,可以在LINQ中编写子查询。

Yes, you can write Sub Query in LINQ as well. 是的,您也可以在LINQ中编写Sub Query

 var werkzeuge = from w in dbContext.cpmWerkzeug
  join e in dbContext.cpmEinAusgang
  on w.Id equals e.WerkzeugId
  where w.id = (dbContext.cpmEinAusgang.Max(x => x.id)) AND w.WerkzeugId = WerkzeugId

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM