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

标签 c# linq lambda

我一直在阅读一些帖子,但没有找到解决 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、Lambda 或 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/

相关文章:

c++ - lambda 的生命周期在 const lambda 中捕获引用

java - Java 1.6 中是否有用于类似 lambda 语句的 OOB Command 接口(interface)?

C# 2.0 设计问题 - 从更大的列表创建子列表

c# - 委托(delegate)创建的性能不足

c# - LINQ to Entities 对具有嵌套对象的 Union 的空引用

c# - 多个值包含动态 Linq

generics - 如何在 kotlin 中使用泛型编写 lambda?

c# - 覆盖 ComboBox 的 DrawItem

c# - 文件读取外来字符

c# - 有条件地包含在 EF Core 中