【问题标题】:Creating list of items that are not older than 30 days with Linq [duplicate]使用 Linq 创建不超过 30 天的项目列表 [重复]
【发布时间】:2020-03-25 16:51:45
【问题描述】:

我有一个看起来像这样的方法

public class Site
{
    public virtual ICollection<SalesOrder> soDetails { get; private set; }

    public int? IncomingOSI(Site s)
    {
        PIC_Program_1_0Context db = new PIC_Program_1_0Context();
        List<SalesOrder> so = db.SalesOrders
          .Where(x => x.siteID == s.ID)
          .Where(x => x.DateCreated > DateTime.Now.AddDays(-30)).ToList();
    }
}

但目前这会返回一个错误

'LINQ to Entities 无法识别方法'System.DateTime AddDays(Double)' 方法,并且此方法无法转换为存储表达式。'

这是什么原因?

【问题讨论】:

  • 旁注:您可能搜索了错误消息bing.com/…,但由于某种原因决定不在帖子中显示您的研究结果。由于“这个问题没有显示任何研究工作”,这可能会导致帖子被否决......
  • @AlexeiLevenkov 好的,感谢您的澄清

标签: c# linq-to-entities


【解决方案1】:

将其声明为 linq 表达式之外的变量。

public class Site
{
   public virtual ICollection<SalesOrder> soDetails { get; private set; }

   public int? IncomingOSI(Site s)
   {
      PIC_Program_1_0Context db = new PIC_Program_1_0Context();

      // declare it outside of the expression
      var less30days = DateTime.Now.AddDays(-30);

      List<SalesOrder> so = db.SalesOrders.Where(x => x.siteID == s.ID).Where(x => x.DateCreated > less30days).ToList();
   }
}

这里的答案解释了原因; Linq 将无法运行其他 C# 代码,因为将其转换为 sql 表达式时会出现问题。

LINQ to Entities does not recognize the method

【讨论】:

  • 你能不能把这两个Where() 条件合二为一:Where(x =&gt; x.siteID == s.ID &amp;&amp; x =&gt; x.DateCreated &gt; less30days)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-18
  • 2019-11-01
  • 1970-01-01
相关资源
最近更新 更多