[英]LINQ to Entities: queryable extension method not reconized inside where condition
我使用asp.net 4.5 mvc 5與代碼第一實體框架,並有以下問題:
我有兩個型號,“PostBody”和“PostHeader”。 1 PostHeader有1-n PostBodies。 PostBody可以“刪除”(屬性為標志)。
我的擴展方法應該從IQueryable-Object給我每個PostBody,它不會被刪除為IQueryable:
public static IQueryable<TSource> GetActiveVersions<TSource>(this IQueryable<TSource> source)
where TSource : PostBody
{
return source.Where(x => x.Deleted == false);
}
當我做這樣的事情時,這工作正常
var x = db.Bodies.GetActiveVersions().ToList();
或這個
var y = db.Headers.FirstOrDefault().Bodies.AsQueryable().GetActiveVersions().ToList();
等等 - 但是當我使用我的擴展方法作為例如where方法中的表達式參數的一部分時,我遇到了NotSupportedException:
var z = db.Headers.Where(h => h.Bodies.AsQueryable().GetActiveVersions().Count() > 0).ToList();
System.NotSupportedException: LINQ to Entities does not recognize the method 'System.Linq.IQueryable`1[WebApplication5.Models.PostBody] GetActiveVersions[PostBody](System.Linq.IQueryable`1[WebApplication5.Models.PostBody])' method, and this method cannot be translated into a store expression.
我究竟做錯了什么? 或 - 我如何在where條件下使用我的擴展方法?
也許解析器無法解析linq表達式中的擴展方法。 您可以嘗試集中您的條件並將其用作表達式樹,用於示例:
public static Expression<Func<TSource, bool>> GetActiveVersions()
where TSource : PostBody
{
return x => x.Deleted == false;
}
並在您的子查詢(使用linq)中將此表達式應用於樣本:
var z = db.Headers.Where(h => h.Bodies.AsQueryable().Any(GetActiveVersions())).ToList();
而使用Count() > 0
,更喜歡使用.Any()
來避免訪問表的所有記錄。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.