如何工作围绕实体框架日期时间类型的错误

本文关键字:日期 框架 时间 类型 错误 实体 何工作 工作 | 更新日期: 2023-09-27 18:19:01

我想获得所有每月过期的产品,下面是查询:

_customerProductsRepository
    .Where(
        d =>
        !d.ReleaseDate.HasValue &&
        EntityFunctions.AddMonths(d.RenewalDate ?? d.AcquireDate, 1) < now)
    .ToArray();

AcquireDate是第一次购买该产品,RenewalDate是最后一次更新该产品。

由于某种原因,它转换成如下SQL:

SELECT
[Extent1].[CustomerDidId] AS [CustomerDidId],
[Extent1].[DidNumber] AS [DidNumber],
[Extent1].[CountryId] AS [CountryId],
[Extent1].[CustomerId] AS [CustomerId],
[Extent1].[AcquireDate] AS [AcquireDate],
[Extent1].[ReleaseDate] AS [ReleaseDate],
[Extent1].[RenewalDate] AS [RenewalDate],
[Extent1].[RenewalNotificationDate] AS [RenewalNotificationDate]
FROM [dbo].[CustomerDids] AS [Extent1]
WHERE ([Extent1].[ReleaseDate] IS NULL) AND ((DATEADD (month, 1, [Extent1].[Rene
walDate])) < @p__linq__0)

应该有一个case语句引用"??"符号,而不是-它完全删除了AcquireDate列。

我如何绕过它?

如何工作围绕实体框架日期时间类型的错误

已按要求配置属性RenewalDate。因此EF将通过计算"if"条件的结果来优化查询。

你试过这样做吗:

_customerProductsRepository
    .Where(
        d =>
        !d.ReleaseDate.HasValue &&
        (d.RenewalDate.HasValue ? 
              EntityFunctions.AddMonths(d.RenewalDate.Value, 1) < now) :
              EntityFunctions.AddMonths(d.AcquireDate, 1) < now))
    .ToArray();

一种情况下,如果你不能让这个工作作为IQueryable,获得所有的数据作为IEnumerable(调用asEnumerable),然后通过您指定的日期方法过滤。