Expert wanna be
Expert wanna be

Reputation: 10624

LINQ to Entities does not recognize the method?

var tmp = productDBSet.Where(x => x.lastUpdate >= DateTime.MinValue && x.lastUpdate.Value.ToString("MM/yyyy") == curMonth).Select(x => x.ID);

While I run above code, I got this error message:

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

Also I tried,

var tmp = productDBSet.Where(x => x.lastUpdate >= DateTime.MinValue && x.lastUpdate.Value.ToString("MM/yyyy") == curMonth).ToList().Select(x => x.ID);

But same,

How can I solve that?

Upvotes: 1

Views: 784

Answers (3)

user4993223
user4993223

Reputation:

You can not use extension methods in linq queries, since these are unable to get converted to equivalent Sql Queries. You can use following linq:

var tmp = productDBSet.Where(x => x.lastUpdate >= DateTime.MinValue && x.lastUpdate.Month == curMonth && x.lastUpdate.Year == curYear).Select(x => x.ID);

Upvotes: 1

Servy
Servy

Reputation: 203850

As the error message is telling you, the ToString method of DateTime isn't supported.

Since you're just trying to determine if the month and year of the date match a given value, you can just compare the actual month and year, rather than trying to get a string containing the month and year that you compare with.

x.lastUpdate.Value.Year == yearToCompareWith && 
    x.lastUpdate.Value.Month = monthToCompareWith

Upvotes: 3

Marcin Zablocki
Marcin Zablocki

Reputation: 10703

You cannot use ToString() in Linq to Entities. Try something like this (I've assumed that x.lastUpdate is of type "DateTime"):

x.lastUpdate.Month == curMonth && x.lastUpdate.Year == curYear

This happens, because LINQ to Entities is translated to SQL queries, and therefore method ToString is not recognised.

Upvotes: 2

Related Questions