admin

Entity Framework查询中的自定义函数有时会正确翻译,有时会不正确

sql

我有这个功能:

public static IQueryable<Article> WhereArticleIsLive(this IQueryable<Article> q)
{
    return q.Where(x =>
        x != null
        && DateTime.UtcNow >= x.PublishTime
        && x.IsPublished
        && !x.IsDeleted);
}

它在此查询中工作正常:

from a in Articles.WhereArticleIsLive()
where a.Id == 5
select new { a.Title }

但这在稍微复杂一点的查询中不起作用:

from s in Series
from a in Articles.WhereArticleIsLive()
where s.Id == a.SeriesId
select new { s, a }

我收到此错误消息:

NotSupportedException:LINQ to Entities无法识别方法’System.Linq.IQueryable
1[TheFraser.Data.Articles.Article] WhereArticleIsLive(System.Linq.IQueryable1
[TheFraser.Data.Articles.Article])方法,并且该方法无法转换为商店表达式。

知道为什么吗?还有另一种合并查询参数的方法吗?

提前致谢。


阅读 153

收藏
2021-07-01

共1个答案

admin

编辑:克雷格的更正。

我将其保留在这里,因为我认为这是一个有价值的工具:使用linqkit!但不是为了解决这个问题:-)

不用返回IQueryable,而是使用Expression分解谓词。例如,您可以在Article上定义以下静态方法:

public static Expression<Func<Article,bool>> IsLive()
{
    return x =>
    x != null
    && DateTime.UtcNow >= x.PublishTime
    && x.IsPublished
    && !x.IsDeleted
}

然后,确保在构建查询时存储对此表达式的引用,类似(未经测试)的含义:

var isLive = Article.IsLive();

from s in Series
from a in Articles.Where(isLive)
where s.Id == a.SeriesId
select new { s, a }
2021-07-01