开发者

Nested Linq Queries Saga

开发者 https://www.devze.com 2022-12-16 03:01 出处:网络
So I am trying to write something like this: SELECTs.Comp开发者_C百科anyID, s.ShareDate, s.OutstandingShares,

So I am trying to write something like this:

SELECT  s.Comp开发者_C百科anyID, 
        s.ShareDate, 
        s.OutstandingShares, 
        s.ControlBlock 
FROM (
    SELECT MAX(ShareDate) AS Sharedate, 
           CompanyID
    FROM ShareInfo
    WHERE (ShareDate <= @filter_date)
    GROUP BY CompanyID
 ) AS si 
 INNER JOIN
 tblShareInfo AS s ON s.ShareDate = si.Sharedate AND s.CompanyID = si.CompanyID

Essentially this is trying to return the most recent Share Information, we keep a running history. Now I am trying to write something similar to this in LINQ.

Here was my closest attempt:

From a _
In db_context.ShareInfos _
Where a.ShareDate <= filter_date _
Group a By a.CompanyID Into Group _
Select CompanyID, MostRecentShareDate = Group.Max(Function(a) a.ShareDate) _
Join b In db_context.ShareInfos On b.CompanyID Equals a.CompanyID _
Select b.CompanyID, b.ShareDate, b.OS, b.CB()

Unfortunately this does not compile. Obviously I'm not understanding the LINQ syntax somehow. Can anyone steer me in the right direction?

Thanks.


with your last select statement you should use

select new {

CompanyID = b.CompanyID,
ShareDate = b.ShareDate,
OS = b.OS,
CB = b.CB
};

that's a start...


Okay so looks like this needs to be done using two statements:

Dim MostRecentShareDates = _ 
From s2 In query_collection.DBContext.ShareInfos _
Where s2.ShareDate <= filter_date _
Group s2 By s2.CompanyID Into Group _
Select New With { _
                    .CompanyID = CompanyID, _
                    .MostRecentShareDate = Group.Max(Function(s3) s3.ShareDate) _
                }

Return From s In query_collection.DBContext.ShareInfos _
       Join s1 In MostRecentShareDates On s.CompanyID Equals s1.CompanyID And s.ShareDate Equals s1.MostRecentShareDate _
       Select New With { _
                        .CompanyID = s.CompanyID, _
                        .ShareDate = s.ShareDate, _
                        .OS = s.OS, _
                        .CB = s.CB _
                       }

I tried using the 'Let' keyword to embed the first statement into the second, but that would not compile either. Now the nice thing about this is the Linq has delayed execution, so until you traverse the collection returned by the second statement, no SQL gets generated. Linq is then smart enough to combine the two code fragments into one SQL statement, essentially exactly the same statement as I wrote in my original SQL above.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号