In a LINQ-to-Entities query, how do you utilize a custom property?

.net c# entity-framework linq-to-entities

Question

I'm in a class.Post It is a model with zzz-8 zzz. It has a characteristic like this:

public bool Showable {
  get {
    return this.Public && this.PublishedDate > DateTime.now
  }
}

It may be used to a question like this:

from p in db.Posts where p.Showable select p;

nevertheless, when I use it in a property like this

public IEnumerable<Post> ShowablePosts {
  get {
    return from p in db.Posts where p.Showable select p;
  }
}

thus I am unable to:

from p in ShowablePosts where p.Id > 42 select p;

It reads:

The specified type member 'Showable' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.

1
16
4/8/2015 9:47:36 PM

Popular Answer

If you write the property as an, you may accomplish this.Expression which SQL can translate.

This is the procedure.

It's a generic answer to a difficult issue, therefore that makes it a little tricky.

The fundamental concept is that runtime SQL translation of compiled code, such as your property, is not possible with LINQ to Entities (like all LINQ providers). LINQ to Objects is capable of executing compiled code, but not translate code. However, they translate anExpression<T> . You might therefore write:

public static Expression<Func<Post, bool>> WhereActive
{
    get
    {
        return p => p.Public && p.PublishedDate > DateTime.Now;
    }
}

You might then type:

public IEnumerable<Post> ShowablePosts 
{
    get 
    {
        return db.Posts.Where(WhereActive);
    }
}

LINQ to Entities may be able to translate it. This concept is generalized by the code in the article I linked.

20
2/11/2010 2:10:33 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow