How can I use external expressions in Linq with EF4 (and LINQKit)?

Posted by neo on Stack Overflow See other posts from Stack Overflow or by neo
Published on 2010-03-30T09:28:29Z Indexed on 2010/03/30 9:33 UTC
Read the original article Hit count: 682

I want to separate out often used expressions in linq queries. I'm using Entity Framework 4 and also LINQKit but I still don't know how I should do it the right way. Let me give you an example:

Article article = dataContainer.Articles.FirstOrDefault(a => a.Id == id);

IEnumerable<Comment> comments =
  (from c in container.Comments
   where CommentExpressions.IsApproved.Invoke(c)
   select c);


public static class CommentExpressions
{
    public static Expression<Func<Module, bool>> IsApproved
    {
        get
        {
            return m => m.IsApproved;
        }
    }
}

Of course the IsApproved expression would be something much more complicated.

The problem is that the Invoke() won't work because I didn't call .asExpandable() from LINQKit on container.Comments but I can't call it because it's just an ICollection instead of an ObjectSet.

So my question is: Do I always have to go through the data context when I want to include external expressions or can I somehow use it on the object I fetched (Article)?

Any ideas or best practices? Thanks very much! neo

© Stack Overflow or respective owner

Related posts about LINQ

Related posts about entity-framework