在实体框架查询自定义函数有时翻译正确,有时不 [英] Custom function in Entity Framework query sometimes translates properly, sometimes doesn't

查看:128
本文介绍了在实体框架查询自定义函数有时翻译正确,有时不的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个功能:

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

和它在此查询工作得很好:

And it works just fine in this query:

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

不过,这并不在此只是稍微更复杂的查询工作:

But it doesn't work in this only slightly more complex query:

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

我收到此错误信息:

引发NotSupportedException:LINQ到实体无法识别方法System.Linq.IQueryable 1 [TheFraser.Data.Articles.Article] WhereArticleIsLive(System.Linq.IQueryable 1 [TheFraser.Data.Articles.Article])的方法,而这种方法不能被翻译成店的表情。

NotSupportedException: LINQ to Entities does not recognize the method 'System.Linq.IQueryable1[TheFraser.Data.Articles.Article] WhereArticleIsLive(System.Linq.IQueryable1[TheFraser.Data.Articles.Article])' method, and this method cannot be translated into a store expression.

任何想法,为什么?有另一种方式来巩固查询参数像这样提前?

Any idea why? Is there another way to consolidate query parameters like this?

感谢。

推荐答案

编辑:由Craig更正。

corrections by Craig.

我要离开这个在这里,是因为我认为这是一个有价值的工具:使用的 linqkit !但不适合解决,虽然这个问题: - )

I'm leaving this here, because I think it's a valuable tool: Use linqkit! But not for solving this question though :-)

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

Instead of returning IQueryable, use Expression to factor out predicates. E.g. you could define the following static method on Article:

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



然后,确保存储到这个表达式的引用时建设您的查询,沿(未测试)线的东西:

Then, ensure to store a reference to this expression when building your query, something along the lines of (not tested):

var isLive = Article.IsLive();

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

这篇关于在实体框架查询自定义函数有时翻译正确,有时不的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆