c# - LINQ to Entities does not support extension method? -
i have 2 extension methods
public static iqueryable<t> currentversion(this iqueryable<t> queryable, datetime date) { return queryable.where(p => p.creationdate>date); } public static ienumerable<t> currentversion(this ienumerable<t> queryable, datetime date) { return queryable.where(p => p.creationdate>date); }
my model is
public class group { .. icollection<groupmembers> groupmembers { get; set; } }
when use extension method in query ok
var q = db.groups.currentversion(); var result = q.tolist();
but when use in flowing query error
var q = db.groups.selectmany(p => p.groupmembers.asqueryable().currentversion(date)); or var q = db.groups.selectmany(p => p.groupmembers.asenumerable().currentversion(date)); var result = q.tolist(); // here error
error:
linq entities not recognize method 'system.linq.iqueryable
1[..](system.linq.iqueryable
1[..., system.datetime)' method, , method cannot translated store expression.
now have 2 questions:
i googled error , found many problems same question in stackoverflow. answers "linq entities can't convert extension method sql query". grateful if me know, why first query not raise errors?
how can change extension method can recognized linq-to-entities?
linq query needs translated sql. when have currentversion extension called inline this:
db.groups.currentversion();
then ef invokes currentversion method, gets resulting iqueryable object , transforms in query. on other hand in case of query:
var q = db.groups.selectmany(p => p.groupmembers.asqueryable().currentversion(date));
the inner expression in selectmany may not ever invoked in code! meant translated sql. treated expression object , parsed, in case contains invoke expression invoking method cannot translated sql obvious reason. within selectmany lambda parameer cannot invoke method, have provide there proper expression. valuable thing provided currentversion method filtering expression. change method this:
public static expression<t, bool> currentversion( datetime date) { return p => p.creationdate > date; }
an use this:
var q = db.groups.where(expressionshelper.currentversion(date)); ... expression<t, bool> filterexpression = expressionshelper.currentversion(date); db.groups.selectmany(p => p.groupmembers.asqueryable().where(filterexpression));
if whish may stil have extension method sharing filtering logic new method:
public static iqueryable<t> currentversion(this iqueryable<t> queryable, datetime date) { return queryable.where(expressionshelper.currentversion(date)); }
Comments
Post a Comment