如何使用lambda与leftjoin和isnull检查

时间:2015-05-08 11:52:24

标签: c# linq lambda left-join isnull

我很近但没有雪茄。在SQL中我可以在我的where子句中使用ISNULL,但我似乎无法通过linq传递它。

var q3 =(
    from Prin in HR
        .Where(Prin => (Prin.JobName == "Pricipal-Elementary")  && 
                        (ASup =>((String.Compare(ASup.UnitName,null) >=0)&&
                        (String.Compare(ASup.UnitName ,"%Learning%"))
                        ))
                )
    //WHERE Prin.JobName = 'Principal-Elementary'
    //AND ISNULL(ASup.UnitName,'') LIKE '%Learning%'
    //ORDER BY SchoolName
    from ASup in HR
        .Where(ASup => ASup.ADAccount == Prin.ChiefADAccount)
        .DefaultIfEmpty()
    from Sch in UnitToSchools
        .Where(Sch => Sch.UnitCode == Prin.UnitCode)
        .DefaultIfEmpty()
    select new
    {
     SchoolName = Prin.UnitName
    ,SchoolId = Sch.SchoolDetailFCSId
    ,PrincipalID = Prin.ADAccount
    ,LComm = ASup.UnitName
    ,AreaSupId = Prin.ChiefADAccount

    }
);
var xyz = (q3).ToList();

//Below is the correct query in SQL
    SELECT Prin.UnitName AS SchoolName
           , Sch.SchoolDetailFCSId AS SchoolId
         , Prin.ADAccount AS PrincipalID
           , ASup.UnitName AS LComm
         , Prin.ChiefADAccount AS AreaSupID
      FROM IP_F.dbo.HR Prin
      LEFT OUTER JOIN IP_F.dbo.HR ASup
        ON ASup.ADAccount = Prin.ChiefADAccount
      LEFT OUTER JOIN IP_F.dbo.UnitToSchool Sch
        ON Sch.UnitCode = Prin.UnitCode
    WHERE Prin.JobName = 'Principal-Elementary'
       AND ISNULL(ASup.UnitName,'') LIKE '%Learning%'
    ORDER BY SchoolName

任何帮助将不胜感激。显然我不能在lambda上使用String.Compare。所以我被卡住了......

先谢谢。

2 个答案:

答案 0 :(得分:1)

您的查询的这一部分:

 ISNULL(ASup.UnitName,'') LIKE '%Learning%'

将以LINQ编写

(ASup.UnitName ?? '').Contains("Learning")

答案 1 :(得分:0)

你尝过类似的东西吗?

(String.IsNullOrEmty(ASup.UnitName) ? string.Empty : ASup.UnitName).Contains("Learning")