在LINQ到实体查询一个人如何使用自定义属性?自定义、如何使用、实体、属性

2023-09-03 01:58:30 作者:醉後抉定愛上你

我有一个类发布这是一个实体框架模型。它包含一个属性是这样的:

 公共BOOL Showable {
  得到 {
    返回this.Public和放大器;&安培; this.PublishedDate> DateTime.now
  }
}
 

我可以在这样的查询中使用它:

 由对在db.Posts那里p.Showable器选择p;
 

但是当我有一个使用它的属性,这样

 公开的IEnumerable<邮政> ShowablePosts {
  得到 {
    从对在db.Posts那里p.Showable器选择p返回;
  }
}
 
C 我用linq联合查询返回一个实体对象,怎么才能返回实体对象

那么,我不能做的:

 由对在ShowablePosts那里p.Id> 42选择磷;
 

它说:

  

指定的类型成员的Showable是不是实体支持LINQ。只有初始化,实体成员和实体导航属性都支持。

解决方案

可以,如果你写的财产做一个防爆pression 这是翻译到SQL。

这里是如何做到这一点。

这是一个有点复杂,因为它是一个通用的解决方案,以一个复杂的问题。

的总体思路是这样的:LINQ到实体(如所有的LINQ提供程序)不能转换编译code喜欢你的财产转换成SQL在运行时。 LINQ到对象可以的执行的编译code,但它不能的翻译的吧。但是,他们的可以的转换的防爆pression< T> 。所以,你可以写:

 公共静态防爆pression< Func键<邮政,布尔>> WhereActive
{
    得到
    {
        返回P => p.Public&功放;&安培; p.PublishedDate> DateTime.Now;
    }
}
 

然后,你可以写:

 公开的IEnumerable<邮政> ShowablePosts
{
    得到
    {
        返回db.Posts.Where(WhereActive);
    }
}
 

...和LINQ to实体可以转化的。在code。在文章中,我链接推广这个想法。

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

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

I can use it in a query like this:

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

but when I have a property that uses it, like this

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

then I can't do:

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

It says:

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

解决方案

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.