LINQ to Entities无法识别方法'Int32 GetMonth(System.DateTime)'方法

时间:2015-03-26 05:41:49

标签: c# asp.net-mvc linq

我想选择PersianCalendar特殊月份中的项目。

我用这个linq。

 var calendar = new PersianCalendar();
 var month = calendar.GetMonth(DateTime.Now);
 var referreds= _db.Referreds.Where(m => calendar.GetMonth(m.CreatedDateTime) == month);

但我得到错误

  

LINQ to Entities无法识别方法' Int32 GetMonth(System.DateTime)'方法,并且此方法无法转换为商店表达式

如何在linq中选择具有特殊月份的项目?

1 个答案:

答案 0 :(得分:1)

您不能直接在LINQ to Entities中使用PersianCalendar(除其他原因外,因为底层数据库没有明确支持它)。什么会奏效:

  1. 使用 PersianCalendar.ToDateTime
  2. 计算每月的第一天
  3. 计算下个月的第一天
  4. 使用这些值进行查询

    _db.Referreds.Where(m => m.CreatedDateTime> = firstDayOfMonth&& m.CreatedDateTime< firstDayOfNextMonth);

  5. 我在这里假设波斯日历与格里高利历有相同的基本属性。如果没有,我肯定Jon Skeet会介入纠正我。