Linq查询不会返回与SQL查询相同的数据

时间:2018-09-29 00:02:57

标签: c# sql-server entity-framework

我正在使用以下方法获取列表:

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)

返回3!列注释是不可为null的nvarchar(MAX)。

为什么结果不一样?

1 个答案:

答案 0 :(得分:2)

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语句要求的结果是

如果您要模拟SQL语句,请将linq查询更改为此。

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