gpt4 book ai didi

c# - LINQ to Entities : Using DateTime. Lambda 表达式中的 AddMonth

转载 作者:行者123 更新时间:2023-11-30 21:24:43 25 4
gpt4 key购买 nike

我一直在阅读一些帖子,但我没有找到 LINQ To Entities、Lambda 表达式和 DateTime.AddMonth 问题的解决方案。

问题是我正在尝试在 Lambda 表达式中使用 DateTime.AddMonth,但出现此错误:

"LINQ to Entities does not recognize the method 'System.DateTime AddMonths(Int32)' method, and this method cannot be translated into a store expression"

当我执行这段代码时:

List<Orders> orders = context.Orders
.Where(o => o.IdOrderStatus == 1)
.Where(o => o.PaymentDate.Value.AddMonths(o.Products.ProductCategories.CommissionableMonths) > DateTime.Now)
.ToList();

有没有办法避免这种异常但保持相同的行为?

我不太了解 Linq、Lambdas 或 Entity Framework 。

非常感谢您!

Gsus.

最佳答案

您可以在不过滤日期的情况下返回必要的信息,然后再过滤日期。 (当然,我不确定您的数据有多大,因此这可能效率不高。如果是这样,您将需要某种基于 SQL 的解决方案——也许是一个存储过程。)

List<Orders> orders = context.Orders
.Where(o => o.IdOrderStatus == 1)
.ToList();
orders = orders.Where(o.PaymentDate.Value.AddMonths(o.Products.ProductCategories.CommissionableMonths) > DateTime.Now);

这会将查询的 AddMonths 部分转换为 Linq-to-Objects 方法而不是 Linq-to-Entities 调用。

关于c# - LINQ to Entities : Using DateTime. Lambda 表达式中的 AddMonth,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1064620/

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