在我的Custom ObjectContext類中,我將我的實體集合公開爲IObjectSet,以便它們可以進行單元測試。在編譯查詢中使用此ObjectContext並在第722-723頁的「編程實體框架第2版」一書中調用「Include」擴展方法(來自Julie Lerman的博客http://thedatafarm.com/blog/data-access/agile-entity-framework-4-repository-part-5-iobjectset/)時,我遇到了一個問題。 下面是代碼:IObjectSet包含CompiledQuery的擴展方法錯誤
查詢:
public class CommunityPostsBySlugQuery : QueryBase<IEnumerable<CommunityPost>>
{
private static readonly Expression<Func<Database, string, IEnumerable<CommunityPost>>> expression = (database, slug) => database.CommunityPosts.Include("Comments").Where(x => x.Site.Slug == slug).OrderByDescending(x => x.DatePosted);
private static readonly Func<Database, string, IEnumerable<CommunityPost>> plainQuery = expression.Compile();
private static readonly Func<Database, string, IEnumerable<CommunityPost>> compiledQuery = CompiledQuery.Compile(expression);
private readonly string _slug;
public CommunityPostsBySlugQuery(bool useCompiled, string slug): base(useCompiled)
{
_slug = slug;
}
public override IEnumerable<CommunityPost> Execute(Database database)
{
return base.UseCompiled ? compiledQuery(database, _slug) : plainQuery(database, _slug);
}
}
擴展
public static class ObjectQueryExtension
{
public static IQueryable<T> Include<T>(this IQueryable<T> source, string path)
{
var objectQuery = source as ObjectQuery<T>;
return objectQuery == null ? source : objectQuery.Include(path);
}
}
LINQ實體無法識別方法「System.Linq.IQueryable1 [MyPocoObject]包括[ MyIncludedPocoObject](System.Linq.IQueryable1 [MyPocoObject],System.String)'方法,並且此方法不能轉換爲存儲表達式。
如果我在ObjectSet集合而不是IObjectSet上使用這個相同的查詢,它工作正常。如果我只是簡單地運行這個查詢而不進行預編譯,它就能正常工作我在這裏錯過了什麼?
我認爲你的頁碼錯了,272-273也許? – 2010-11-16 19:54:31
@Ryan woops,我的意思是722-723 – Paul 2010-11-16 20:59:36