我试图在IQueryable中比较两个可以为空的DateTime对象(来自数据库),如下所示:
result.FirstOrDefault(x => x.FirstDateTime == secondDateTime)
这在某些开发人员的计算机上正常执行,但它不在我的计算机上。它没有结果。因为如果我将结果转换为这样的列表,它可以工作:
result.ToList().FirstOrDefault(x => x.FirstDateTime == secondDateTime)
当然我不想留下这样的代码,只是为了表明它不是因为在IQueryable中找不到日期
两个值均为UTC。我尝试使用Single
,SingleOrDefault
,First
和Where
全部使用相同的结果。我还尝试将FirstDateTime.Value
与secondDateTime.Value
进行比较。同样,结果相同
IQueryable的提供者是
System.Data.Entity.Internal.Linq.DbQueryProvider。
可能导致这种情况的原因是什么?为什么第一部分在某些计算机上运行,但在其他计算机上却没有,它可以依赖什么?
这是正在生成的SQL:
FROM ( SELECT
[Extent1].[Id] AS [Id],
[Extent1].[OtherProperty1] AS [OtherProperty1],
[Extent1].[Version] AS [Version],
[Extent1].[Submitted] AS [Submitted],
[Extent1].[SubmittedBy] AS [SubmittedBy],
[Extent1].[Created] AS [Created],
[Extent1].[CreatedBy] AS [CreatedBy],
[Extent2].[Value] AS [Value],
[Extent2].[OtherProperty2] AS [OtherProperty2],
[Extent2].[Description] AS [Description],
[Extent2].[Latitude] AS [Latitude],
[Extent2].[Longitude] AS [Longitude],
[Extent2].[OtherProperty3] AS [OtherProperty3],
[Extent2].[OtherProperty4] AS [OtherProperty4],
[Extent2].[FirstDateTime] AS [FirstDateTime],
''0X0X'' AS [C1]
FROM [dbo].[StructuredInformations] AS [Extent1]
INNER JOIN [dbo].[Positions] AS [Extent2] ON [Extent1].[Id] = [Extent2].[Id]
WHERE ([Extent1].[OtherProperty1] = @p__linq__0) AND ([Extent2].
[FirstDateTime] IS NOT NULL) AND ([Extent2].[FirstDateTime] = @p__linq__1)
) AS [Project1]
ORDER BY [Project1].[OtherProperty2] DESC, [Project1].[FirstDateTime] ASC,
[Project1].[Value] ASC',N'@p__linq__0 int,@p__linq__1
datetime2(7)',@p__linq__0=7,@p__linq__1='2016-10-11 11:45:53.6230000'
答案 0 :(得分:1)
问题类似于this - 看起来LINQ提供程序生成的日期时间值的小数秒精度为7(例如2016-10-11 11:45:53.6230000),而SQL中的列定义为datetime,其精度低于7,而datetime2则精度高达7
要解决此问题,您可以将SQL中的列类型从datetime更改为datetime(7)
答案 1 :(得分:0)
IQueryable
不保证订购。 List<T>
。要保持IQueryable
并保持顺序,您应该尝试对IQueryable
进行排序,然后尝试获得第一个结果:
result.OrderBy(y => y.FirstDateTime).FirstOrDefault(x => x.FirstDateTime == secondDateTime)