如何将此SQL查询转换为使用的Lambda或LINQ(where为null)

时间:2014-09-15 09:38:55

标签: c# sql lambda

我一直在尝试修改SQL中的某些数据行以在我的应用程序中进行测试,并且我注意到我在Lambda中的查询会在我预期2387行时返回0行。问题的根源是我在SQL的WHERE子句中使用括号来查看一些空值。这是SQL查询:

SQL

-- THIS WORKS!
select * from vwAppsWithIssues
   where fld1stCheckAllocatedTo = 'nicholasg' and fldStage = 1
   and (fldStopStartDate is null or fldStopEndDate is not null)

-- The query was originally this (doesn't return rows)
  select * from vwAppsWithIssues
  where fld1stCheckAllocatedTo = 'nicholasg' and fldStage = 1
  and (fldStopStartDate = null or fldStopEndDate <> null)

返回0行的LAMBDA查询

public static int GetApplicationsFirstCount(string UserId)
        {
            try
            {
                using (IME_CheckOffEntities IME_CheckOffEntities = new IME_CheckOffEntities())
                {
                    return IME_CheckOffEntities.vwAppsWithIssues
                         .Where(a => a.fld1stCheckAllocatedTo == UserId && a.fldStage == 1 && (a.fldStopStartDate == null || a.fldStopEndDate != null))
                         .ToList().Count;
                }
            }
            catch (Exception ex)
            {
                throw;
            }
        }

更新

使用LINQPad我写了这个表达式:

VwAppsWithIssues
.Where (v => v.Fld1stCheckAllocatedTo == "nicholasg"
&& v.FldStage == 1 
&& (v.FldStopStartDate == null || v.FldStopEndDate != null)).Count()

生成此sql

SELECT COUNT(*) AS [value]
FROM [vwAppsWithIssues] AS [t0]
WHERE ([t0].[fld1stCheckAllocatedTo] = @p0) AND ([t0].[fldStage] = @p1) AND (([t0].[fldStopStartDate] IS NULL) OR ([t0].[fldStopEndDate] IS NOT NULL))

所以现在我有一些我觉得可行的lambda,我只需将它复制到visual studio。

  var count = IME_CheckOffEntities.vwAppsWithIssues
      .Where(v => v.fld1stCheckAllocatedTo == "nicholasg" && v.fldStage == 1 && (v.fldStopStartDate == null || v.fldStopEndDate != null)).Count();

它仍然只返回0行?!我也在C#中使用了正确的userId。

我在c#中的计数也返回0行。知道如何重写这个C#查询吗?

1 个答案:

答案 0 :(得分:2)

来自linqpad的

,我的一个架构

from
    f in Files
where
    f.PubDate == null || f.FilingDate != null
select
    f.IdFile

翻译如下

SELECT 
[Extent1].[idFichier] AS [idFichier]
FROM [dbo].[tableF] AS [Extent1]
WHERE ([Extent1].[datePubliF] IS NULL) OR ([Extent1].[dateDepotF] IS NOT NULL)

所以,在你的情况下,你是否确定UserId值?