Niloo
Niloo

Reputation: 1215

LINQ to Entities does not recognize the method 'Int32 GetMonth(System.DateTime)' method

I want to select items in special month of PersianCalendar .

I use this linq.

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

But i get error

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

How do i select items with special month in linq??

Upvotes: 0

Views: 1096

Answers (1)

Paul-Jan
Paul-Jan

Reputation: 17278

You cannot use the PersianCalendar within LINQ to Entities directly (amongst other reasons, because the underlying databases do not have explicit support for it). What will work:

  1. Calculate the first day of the month using PersianCalendar.ToDateTime
  2. Calculate the first day of the next month
  3. Use those values to query

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

I am assuming here that the Persian calendar has the same basic properties as the Gregorian calendar. If not, I'm sure Jon Skeet will step in to correct me.

Upvotes: 1

Related Questions