score:1
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
iqueryable
toienumerable
:return getallproducts() .asenumerable() .where(m => equals(dateutilities.extractyear(m.productcreationdate), year)) .asqueryable();
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):
return context .products .sqlquery("select * from products where substring(productcreationdate, 1, 4) = '2012'") .asqueryable();
note that i was lazy and hardcoded the sql. you should probably parametrize it and make sure you avoid any sql injection attacks.
score:1
you could do the extraction inline, something like this:
public iqueryable<products> getcreatedproducts(int year)
{
string syear = year.tostring();
return getallproducts().where(m => m.productcreationdate.substring(0,4) == syear);
}
score:2
i don't think this is really a bug so much as a limitation -- there's no sql version of extractyear
, so it's not possible to execute this query.
you'll have to rewrite the query to either use only sql-compatible commands (like some other answers have shown) or pull lots of data out of the database and do the filtering with linq-to-objects (this could potentially be very expensive, depending on what you're querying and how many of the records match).
score:4
my first question would be why are you storing a date in the database as a string? store it as a date and use data comparison against it through linq.
the issue that you're coming up against is linq doesn't understand what the method extractyear is when it tries to compile your linq statement to raw sql
edit another alternative would be to create a view in the database and query against the view with a computed column that represents the string value as a datetime.
score:4
in this case you could go the other way:
getallproducts().where(m => m.productcreationdate.startswith(year.tostring()));
rather than extract the year from the string, find all strings beginning with the year you're after.
i'm not sure if these will work for the month and day searches:
var monthstring = string.format("{0:00}", month);
getallproducts().where(m => m.productcreationdate.substring(4,2) == monthstring);
var daystring = string.format("{0:00}", day);
getallproducts().where(m => m.productcreationdate.substring(6,2) == daystring);
Source: stackoverflow.com
Related Query
- Workaround to use a method within a LINQ expression
- .NET LINQ Call Method with Out Parameters Within Query and use Out Values
- How can l use Regex.Replace method within LINQ
- Comparing dates within LINQ gives error - Method cannot be translated into a store expression
- C# Pass lambda expression field into method and use field in linq query
- How to extend LinqKit and use a custom method within a linq query?
- how to translate a linq expression into sql string use c# code
- How can I use a method or Expression in a Linq query?
- Code equivalent to the 'let' keyword in chained LINQ extension method calls
- LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression
- How to retrieve last 5 records using LINQ method or query expression in C#
- LINQ to Entities does not recognize the method 'Int32 Int32(System.String)' method, and this method cannot be translated into a store expression
- LINQ to Entities does not recognize the method 'Int32 ToInt32(System.Object)' method, and this method cannot be translated into a store expression
- How to use LINQ to order within groups
- LINQ to Entities does not recognize the method 'Int32 Parse(System.String)' method, and this method cannot be translated into a store expression
- How to: Use async methods with LINQ custom extension method
- Enumerable.Empty<T>().AsQueryable(); This method supports the LINQ to Entities infrastructure and is not intended to be used directly from your code
- Entity Framework LINQ Expression on object within object
- How to use a Func in an expression with Linq to Entity Framework?
- LINQ WHERE method alters source collection
- NHibernate linq - Use lambda expression in place of formula attribute on mapping
- How do I use "Into" LINQ expression in VB.NET?
- LINQ to Entities does not recognize the method 'Boolean HasFlag(System.Enum)' when creating the expression via System.Linq.Expressions.Expression
- How to reuse a linq expression for 'Where' when using multiple source tables
- How do I use an array of values in a LINQ Expression builder?
- Differences in LINQ vs Method expression
- LINQ to Entities: Why can't I use Split method as condition?
- extracting method name from linq expression
- Convert Method to Linq Expression for query
- LINQ Source Code Available
More Query from same tag
- How to create an identity column within a lambda?
- How do I group by an ID within a child collection
- Insert new XML node using LINQ
- Validate file extensions match approved list
- Database relationships and "structure"
- How to compare only date part with linq expression?
- `from..where` or `FirstOrDefault` in LINQ
- LINQ Joining 2 tables
- How to bind gridview using linq/Entity Framework?
- T-SQL to LINQ to SQL using Navigation Properties
- Narrowing a result set using LINQ
- update value of Key in key value pair
- Getting all values from Checkboxlist
- Duplicates while querying Three tables to get Common values using LINQ.
- PowerShell's equivalent of LINQ All, or how can I verify all the items in the collection are equal to specific value?
- Retrieving strongly typed Property names using Expression Trees
- Linq check if list is in another list
- How do I write a LINQ query which will generate a JSON string with the following format?
- Creating a list filled with new instances of an object
- Boolean column in Microsoft Access and filtering data using linq
- Plinq gives different results from Linq - what am I doing wrong?
- Getting multiple records for same value in JSON
- Max return value if empty query
- How to fetch desired elements out of every inner List?
- How to add namespace to xml using linq xml
- Linq insert statement with return value
- Linq if DateTime field is older than X hours
- Linq Query For Self Referencing Object to Get Childless Elements
- How to convert LINQ query data to WPF/MVVM List
- C# aggregate in a better time complexity