Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/powerbi/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 实体框架查询中的自定义函数有时可以正确转换,有时不能';T_C#_Sql_Linq_Entity Framework - Fatal编程技术网

C# 实体框架查询中的自定义函数有时可以正确转换,有时不能';T

C# 实体框架查询中的自定义函数有时可以正确转换,有时不能';T,c#,sql,linq,entity-framework,C#,Sql,Linq,Entity Framework,我有这个功能: public static IQueryable<Article> WhereArticleIsLive(this IQueryable<Article> q) { return q.Where(x => x != null && DateTime.UtcNow >= x.PublishTime && x.IsPublished &&

我有这个功能:

public static IQueryable<Article> WhereArticleIsLive(this IQueryable<Article> q)
{
    return q.Where(x =>
        x != null
        && DateTime.UtcNow >= x.PublishTime
        && x.IsPublished
        && !x.IsDeleted);
}
但它在这个稍微复杂一点的查询中不起作用:

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.IQueryable
1[TheFraser.Data.Articles.Article])方法,并且无法将此方法转换为存储表达式

知道为什么吗?有没有其他方法可以像这样合并查询参数


提前感谢。

编辑:克雷格更正

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

使用表达式来分解谓词,而不是返回IQueryable。例如,您可以在文章上定义以下静态方法:

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

这几乎是正确的。(1)
Expression
是正确的方法。(2) 对于这个任务,您不需要LINQKit(这对于其他东西来说非常有用),也不需要编译等。(3)关键是存储对表达式的引用,即:
expression isLive=Article.isLive();从文章中的a系列中的s。Where(isLive)
@Craig Stuntz:谢谢你的反馈,我相应地更新了我的答案,所以这就是表达式的用途。也谢谢linqkit,我相信它会派上用场的。
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 }