【问题标题】:LINQ Where in MAXLINQ 在 MAX 中的位置
【发布时间】:2012-03-11 21:39:18
【问题描述】:

我目前有这个 linq 语句:

from s in SubContentRevisions
where s.SubContentID.Equals("e3f319f1-65cc-4799-b84d-309941dbc1da")
&& s.RevisionNumber == (SubContentRevisions.Max(s1 => s1.RevisionNumber))
select s

生成此 SQL(根据 LINQPad):

-- Region Parameters
DECLARE @p0 UniqueIdentifier = 'e3f319f1-65cc-4799-b84d-309941dbc1da'
-- EndRegion
SELECT [t0].[SubContentRevisionID], [t0].[SubContentID], [t0].[RevisionNumber], [t0].[RevisionText], [t0].[CreatedDate], [t0].[ModifiedDate]
FROM [SubContentRevision] AS [t0]
WHERE ([t0].[SubContentID] = @p0) AND ([t0].[RevisionNumber] = ((
    SELECT MAX([t1].[RevisionNumber])
    FROM [SubContentRevision] AS [t1]
    )))

如何让它生成这条 SQL 语句?我似乎在任何地方都找不到任何相关的东西。 (我需要它在子查询中添加 where 子句)

-- Region Parameters
DECLARE @p0 UniqueIdentifier = 'e3f319f1-65cc-4799-b84d-309941dbc1da'
-- EndRegion
SELECT [t0].[SubContentRevisionID], [t0].[SubContentID], [t0].[RevisionNumber], [t0].[RevisionText], [t0].[CreatedDate], [t0].[ModifiedDate]
FROM [SubContentRevision] AS [t0]
WHERE ([t0].[SubContentID] = @p0) AND ([t0].[RevisionNumber] = ((
    SELECT MAX([t1].[RevisionNumber])
    FROM [SubContentRevision] AS [t1]
    WHERE [SubContentID] = @p0 -- **********Adds the where clause**********
    )))

【问题讨论】:

    标签: c# linq-to-sql


    【解决方案1】:

    我想你想要:

    from s in SubContentRevisions
    where s.SubContentID.Equals("e3f319f1-65cc-4799-b84d-309941dbc1da")
      && s.RevisionNumber == (SubContentRevisions.Where(s.SubContentID.Equals("..."))
                                                 .Max(s1 => s1.RevisionNumber))
    select s
    

    或者,更清楚地说:

    var specificSubContents = SubContentRevisions.Where(s => 
                   s.SubContentID.Equals("e3f319f1-65cc-4799-b84d-309941dbc1da")
    
    var query = from s in specificSubContents
                where s.RevisionNumber = s.Max(s1 => s1.RevisionNumber)
                select s;
    

    或者,听起来您实际上可以这样做:

    var latest = (from s in SubContentRevisions
                  where s.SubContentID.Equals("e3f319f1-65cc-4799-b84d-309941dbc1da")
                  orderby s.RevisionNumber descending
                  select s).FirstOrDefault();
    

    【讨论】:

    • 哇...我不敢相信我没有尝试过。
    【解决方案2】:

    如何将where子句添加到子查询(最大):

    from s in SubContentRevisions
    where s.SubContentID.Equals("e3f319f1-65cc-4799-b84d-309941dbc1da")
       && s.RevisionNumber == (SubContentRevisions
                                       .Where(s1 => s1.SubContentID.Equals(s.SubContentID))
                                       .Max(s1 => s1.RevisionNumber))
    select s
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-13
      • 1970-01-01
      相关资源
      最近更新 更多