简体   繁体   English

使用INNER JOIN()将SQL转换为LINQ?

[英]Converting SQL to LINQ with INNER JOIN()?

I am struggling with how to write the below equivalent as LINQ. 我正在努力将下面的等价物写为LINQ。 Truly I guess I am only struggling with how I represent the INNER JOIN () portion. 确实,我想我只是在如何表示INNER JOIN ()部分而苦苦挣扎。 Is that called a Nested Join? 这称为嵌套联接吗? Anonymous Join? 匿名加入? I am not even sure. 我什至不确定。 Anyway, big thanks to anyone who can point me true. 无论如何,非常感谢任何能指出我真实观点的人。 Even if it is just what this is called so I can BING it properly. 即使这就是所谓的名称,所以我也可以对其进行适当的Bing处理。

SELECT p.PersonID, p.FirstName, p.MiddleName, p.LastName, cp.EnrollmentID, cp.EnrollmentDate, cp.DisenrollmentDate
FROM vwPersonInfo AS p
    INNER JOIN (
    SELECT c.ClientID, c.EnrollmentID, c.EnrollmentDate, c.DisenrollmentDate
    FROM tblCMOEnrollment AS c
        LEFT OUTER JOIN tblWorkerHistory AS wh
        ON c.EnrollmentID = wh.EnrollmentID
            INNER JOIN tblStaffExtended AS se
            ON wh.Worker = se.StaffID
    WHERE (wh.EndDate IS NULL OR wh.EndDate >= getdate())
    AND wh.Worker = --WorkerID Param Here
) AS cp
ON p.PersonID = cp.ClientID
ORDER BY p.PersonID

just put the inner query in its own variable. 只需将内部查询放在其自己的变量中即可。 (It will be translated into one single SQL expression) (它将转换为一个单独的SQL表达式)

var innerQuery = from x in db.tblCMOEnrollment
                 where ...
                 select ...;

var query = from a in vwPersonInfo
            join b innerQuery on p.PersonID equals cp.ClientID
            select ...;

I think you can do this by writing a second method and joining on that method: 我认为您可以通过编写第二种方法并加入该方法来做到这一点:

private static IEnumerable<Table> GetData(int joinKey)
    {
        return (from x in context.TableB.Where(id => id.Key == joinKey select x).AsQueryable();
    }

Then you can do your normal query: 然后,您可以执行常规查询:

var query = from c in context.TableA
join GetData(c.PrimaryKeyValue) 

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

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