In my ASP.NET MVC3 application I have the following method that use EF entities:
public IQueryable<Products> GetCreatedProducts(int year)
{
return GetAllProducts().Where(m => Equals(DateUtilities.ExtractYear(m.ProductCreationDate), year));
}
ProductCreationDate is a field stored in the database as string “YYYYMMddhhmm”.
int DateUtilities.ExtractYear(string date) is a method that I created in order to get the year from the string. Similarly I use ExtractMonth and ExtractDay.
However when I execute my application it launches an NotSupported exception:
“LINQ to Entities does not recognize the method ‘Int32 ExtractYear(System.String)’ method, and this method cannot be translated into a store expression.”
By googling the problem I found out that it is a bug in LINQ to Entities Anybody knows a workaround?
You get the exception because you work with
IQueryable. Entity Framework will try to translate the predicate in the where clause into SQL but EF doesn’t know how to translate your method.If you don’t want to (or can’t) change the database you still have a few options:
Pull all rows to the client side and do the filtering on the client. You do this by changing from
IQueryabletoIEnumerable:To be more efficient you can use your own SQL (this requires EF 4.1 and only avoid pulling all products to the client, not the scan on the server):
Note that I was lazy and hardcoded the SQL. You should probably parametrize it and make sure you avoid any SQL injection attacks.