如何解决实体框架日期时间类型错误?

时间:2011-12-30 08:29:51

标签: c# entity-framework entity-framework-4.1 entity-functions

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

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

AcquireDate 是首次购买该产品,续订日期是该产品的最后一次更新。

由于某种原因,它转换为此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)

应该有一个案例陈述,指的是'??'签名,相反 - 它完全删除了AcquireDate列。

我该如何走动?

3 个答案:

答案 0 :(得分:1)

您已根据需要配置了属性RenewalDate。因此,EF将通过评估“if”条件的结果来优化查询。

答案 1 :(得分:0)

你有没有试过这样做:

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

答案 2 :(得分:0)

如果您无法将此作为IQueryable工作,将所有数据作为IEnumerable(调用asEnumerable)获取,然后通过您指定的日期方法过滤掉,则会出现一种情况。