How does one use a custom property in a LINQ-to-Entities query?

后端 未结 3 1068
花落未央
花落未央 2020-12-15 07:20

I have a class Post which is an Entity Framework model. It contains a property like this:

public bool Showable {
  get {
    return this.Public          


        
相关标签:
3条回答
  • 2020-12-15 07:36

    I think easiest way to do this is using Computed attribute of DelegateDecompiler.EntityFramework package that mentioned in this answer.

    0 讨论(0)
  • 2020-12-15 07:38

    Unfortunately, the Entity Framework simply does not support computed properties (that is to say, a property that returns a computed value rather than a reference to a backing field) but it may be supported at a future date.

    0 讨论(0)
  • 2020-12-15 07:51

    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.

    0 讨论(0)
提交回复
热议问题