实体框架查询中的自定义函数有时可以正确地进行翻译,有时候不会 [英] Custom function in Entity Framework query sometimes translates properly, sometimes doesn't
问题描述
我有这个功能:
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 to Entities不识别方法'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.IQueryable
1[TheFraser.Data.Articles.Article] WhereArticleIsLive(System.Linq.IQueryable
1[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屋!