You can do this if you write the property as an Expression
which is translatable to SQL.
Here's how to do it.
That's a bit complicated, because it's a general solution to a complicated problem.
The general idea is this: LINQ to Entities (like all LINQ providers) can't translate compiled code like your property into SQL at runtime. LINQ to Objects can execute compiled code, but it can't translate it. But they can translate an Expression<T>
. So you could write:
public static Expression<Func<Post, bool>> WhereActive
{
get
{
return p => p.Public && p.PublishedDate > DateTime.Now;
}
}
Then you could write:
public IEnumerable<Post> ShowablePosts
{
get
{
return db.Posts.Where(WhereActive);
}
}
...and LINQ to Entities could translate that. The code in the post I link generalizes this idea.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…