简体   繁体   English

Linq 查询不工作,但其等效 SQL 服务器查询工作

[英]Linq query not working but its equivalent SQL Server query is working

Following SQL query works fine (Give expected results) in SQL Server.以下 SQL 查询在 SQL 服务器中工作正常(给出预期结果)。

SELECT * FROM ImportedReportData IRD 
INNER JOIN ImportedReport IR ON IRD.ImportedReportId = IR.Id
WHERE 
IR.StartDate >= CONVERT(DATETIME, '7/1/2022 12:00:00 AM') AND IR.EndDate <= CONVERT(DATETIME, '7/31/2022 11:59:59 PM')

But when I use equivalent Linq (C# / ASP.Net) its not working as expected (Empty result set returned).但是当我使用等效的 Linq (C#/ASP.Net) 时,它没有按预期工作(返回空结果集)。

My Linq statement is我的 Linq 声明是

var ImportedReportDataList = DbContext.ImportedReportDataCRRs.Where(w =>
                (w.ImportedReport.StartDate.Value >= StartDate && w.ImportedReport.EndDate.Value <= EndDate)).ToList();

-- Update Starts -- -- 更新开始 --

Linq converts into following SQL query Linq 转换为以下 SQL 查询

exec sp_executesql N'SELECT 
    [Extent1].* 
    FROM  
    [dbo].[ImportedReportDataCRR] AS [Extent1]
    INNER JOIN [dbo].[ImportedReport] AS [Extent2] ON [Extent1].[ImportedReportId] = [Extent2].[Id]
    WHERE 
    ([Extent2].[StartDate] >= @p__linq__0) AND 
    ([Extent2].[EndDate] <= @p__linq__1)',N'@p__linq__0 datetime2(7),@p__linq__1 datetime2(7)',@p__linq__0='2022-07-01 00:00:00.0010000',@p__linq__1='2022-07-31 23:59:59.9970000'

ie Linq is converting StartDate and EndDate into datetime2(7) which is creating issue.即 Linq 正在将 StartDate 和 EndDate 转换为 datetime2(7),这会产生问题。

-- Update Ends -- -- 更新结束 --

Variable StartDate = 7/1/2022 12:00:00 AM变量 StartDate = 7/1/2022 12:00:00 AM

Variable EndDate = 7/31/2022 11:59:59 PM可变结束日期 = 2022 年 7 月 31 日晚上 11:59:59

ImportedReport.StartDate = 2022-07-01 00:00:00.000 (DB field value) ImportedReport.StartDate = 2022-07-01 00:00:00.000(数据库字段值)

ImportedReport.EndDate = 2022-07-31 00:00:00.000 (DB field value) ImportedReport.EndDate = 2022-07-31 00:00:00.000(数据库字段值)

As mentioned in the comments, don't try to simulate BETWEEN where you find the end of a date range.正如评论中提到的,不要尝试在找到日期范围结束的地方模拟BETWEEN This is problematic because different data types consider the "end" of a period differently.这是有问题的,因为不同的数据类型以不同的方式考虑周期的“结束”。 In this case, much better to say "greater than or equal to the first of July, and less than the first of August."在这种情况下,最好说“大于或等于 7 月 1 日,小于8 月 1 日”。 Also using non-regional and unambiguous date formats:还使用非区域和明确的日期格式:

SELECT <cols>
FROM dbo.ImportedReportData AS IRD 
INNER JOIN dbo.ImportedReport AS IR ON IRD.ImportedReportId = IR.Id
WHERE IR.StartDate     >= '20220701'
  AND IR.EndDate       <  '20220801'
  AND IRD.EmployeeName =  'test';

Please read all of the links at Dating Responsibly .请阅读负责任约会的所有链接。

I suppose in Linq you could say:我想在 Linq 你可以说:

&& w.ImportedReport.EndDate.Value 
   < { whatever you do in Linq to add a day to EndDate }

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

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