gpt4 book ai didi

c# - LINQ where 子句中的 DateTime 属性错误

转载 作者:太空狗 更新时间:2023-10-29 22:56:36 28 4
gpt4 key购买 nike

我有一个非常简单的方法,它使用一些 LINQ 来访问我的数据库中的数据。

我有一些项目正在存储它们的创建日期。日期包括一个偏移量,因此它在数据库中存储为 datetimeoffset 类型。我正在尝试按日期过滤项目,为此我需要减去偏移时间以比较它们:

public async Task<IEnumerable<Item>> GetItems(DateTime? startDate)
{
var items = _dbContext.Items
.AsQueryable();

if (startDate != null)
{
items = items.Where(i =>
i.DateCreated.DateTime.AddHours(i.DateCreated.Offset.Hours) >= startDate.Value);
}

return await items
.ToListAsync();
}

但是当 ToListAsync() 被调用时,我得到这个错误:

Error generated for warning 'Microsoft.EntityFrameworkCore.Query.QueryClientEvaluationWarning: The LINQ expression 'where ([e].DateCreated.DateTime.AddHours(Convert([e].DateCreated.Offset.Hours, Double)) >= __startDate_Value_0)' could not be translated and will be evaluated locally.'. This exception can be suppressed or logged by passing event ID 'RelationalEventId.QueryClientEvaluationWarning' to the 'ConfigureWarnings' method in 'DbContext.OnConfiguring' or 'AddDbContext'.

问题似乎与 AddHours 方法有关,如果我将其删除,它就可以正常工作。但我不知道是否有办法在不使用该方法的情况下使其正常工作。

我可以在这里使用不同的策略吗?

最佳答案

DateTime.AddHours 方法的实际翻译支持的。

问题是目前 EF Core 无法转换 DateTimeOffset 的大部分(如果不是全部)成员,在这种特殊情况下 - DateTime 属性(与 偏移量DateTimeUtc 等)。

幸运的是,它确实支持DateTimeOffset 比较的转换,所以解决方案是换一种方式——将DateTime 参数转换为DateTimeOffset 并在查询中进行简单的比较,例如

if (startDate != null)
{
// Note: must be a variable outside the query expression tree
var startDateOffset = new DateTimeOffset(startDate.Value);
items = items.Where(i => i.DateCreated >= startDateOffset);
}

关于c# - LINQ where 子句中的 DateTime 属性错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55779356/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com