代码之家  ›  专栏  ›  技术社区  ›  hncl

Linq query返回的数据与SQL query返回的数据不同[closed]

  •  0
  • hncl  · 技术社区  · 6 年前

    我正在使用以下命令获取列表:

    var recommend1 = db.Recommendation
        .Where(c => c.Comments != "" && 
                    c.Comments != null && 
                    c.Visit.ClinicId == 5)
        .Select(c => c.VisitId)
        .ToList();
    

    返回0。但是,当我使用以下方法将其作为SQL进行测试时:

    SELECT dbo.Visit.VisitId
    FROM   dbo.Recommendation 
        INNER JOIN dbo.Visit ON dbo.Recommendation.VisitId = dbo.Visit.VisitId
    WHERE  
        (dbo.Visit.ClinicId = '5') AND 
        (dbo.Recommendation.Comments = '') OR
        (dbo.Recommendation.Comments IS NULL)
    

    为什么结果不一样?

    1 回复  |  直到 6 年前
        1
  •  2
  •   Aydin    6 年前
    var recommend1 = db.Recommendation.Where(c => c.Comments != "" || c.Comments != null)
                                      .Where(c => c.Visit.ClinicId == 5)
                                      .Select(c => c.VisitId)
                                      .ToList();
    
    // is not the same as
    
    WHERE(dbo.Visit.ClinicId = '5') 
       AND(dbo.Recommendation.Comments = '') OR (dbo.Recommendation.Comments IS NULL)
    

    您首先指示注释不为null或空的所有结果,sql语句要求注释为空的结果

    var recommend1 = db.Recommendation.Where(c => c.Comments == "" || c.Comments == null)
                                      .Where(c => c.Visit.ClinicId == 5)
                                      .Select(c => c.VisitId)
                                      .ToList();