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