简体   繁体   English

实体框架 - 将 SQL 查询转换为实体框架 Lambda 表达式

[英]Entity Framework - Convert an SQL query to Entity Framework Lambda expression

I have this below query which I need to convert into a lambda expression:我有下面的查询,我需要将其转换为 lambda 表达式:

select t.*
from (
   select DocId, max(Version) as maxversion
   from [DocumentVersion] group by DocId
) as x inner join [DocumentVersion] as t on f.DocId = x.docid and
       t.version = x.maxversion
where t.TestDocId =  12345

These are the column names = Id,DocSecId,Version, DocType, DocId, TestDocId, AppId, RppId, Regions, ExecutedDate EffectiveDate, Icheck, Vcheck, locked, Parentid, childId, LastCheckedId, Modified, Fresh这些是列名称 = Id、DocSecId、Version、DocType、DocId、TestDocId、AppId、RppId、Regions、ExecutedDate EffectiveDate、Icheck、Vcheck、locked、Parentid、childId、LastCheckedId、Modified、Fresh

var dbData = db.DocumentVersion
    .Where(x => listofIds.Contains(x.DocTestId))
    .GroupBy(x => x.DocId).Select(
        g => new
        {
            DocId = g.Key,
            Version = g.Max(x => x.Version),
        })
    .ToList();

So far I have done the below query, but need to include all the columns in the output. In my case, I am getting two parameters as output - Count and Capacity:到目前为止,我已经完成了以下查询,但需要包括 output 中的所有列。在我的例子中,我得到两个参数 output - 计数和容量:

Please help me with the code optimisation as well as the the output generation请帮助我进行代码优化以及 output 生成

As far as I see you have two tables with one to many relationships Document and DocumentVersion and you want to retrieve the latest/max version for the Documents with a given specific list of Ids .据我所知,您有两个具有一对多关系DocumentDocumentVersion的表,并且您希望使用给定的特定Ids列表检索Documents的最新/最大版本。 If this is the case with EF Core 6 you can use the new [MaxBy][1] method and do something like如果 EF Core 6 是这种情况,您可以使用新的[MaxBy][1]方法并执行类似

var documentVersions = db.DocumentVersion
   .Where(x => listofIds.Contains(x.DocTestId))
   .GroupBy(x => x.DocId)
   .Select(g => g.MaxBy(x => x.Version))
   .ToList();

An implementation for EF Core 5 and the below version (including the original EF) prior to introducing the MaxBy operator will use the Max operator and will be something like在引入MaxBy运算符之前,EF Core 5 和以下版本(包括原始 EF)的实现将使用Max运算符,类似于

var documentVersions = db.DocumentVersion
   .Where(x => listofIds.Contains(x.DocTestId))
   .GroupBy(x => x.DocId)
   .Select(g => g.First(x => x.Version == g.Max(y =>  y.Version)))
   .ToList();

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

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