在我的自定义 ObjectContext 类中,我将实体集合公开为 IObjectSet,因此可以对它们进行单元测试。当我在编译查询中使用此 ObjectContext 并调用“包含”扩展方法时遇到问题(来自 Julie Lerman 的博客http://thedatafarm.com/blog/data-access/agile-entity-framework-4- repository-part-5-iobjectset/)和她的书《编程实体框架》第 2 版第 722-723 页。这是代码:
询问:
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 to Entities 无法识别方法 'System.Linq.IQueryable1[MyPocoObject] Include[MyIncludedPocoObject](System.Linq.IQueryable1[MyPocoObject], System.String)' 方法,并且此方法无法转换为存储表达式。
如果我在 ObjectSet 集合而不是 IObjectSet 上使用相同的查询,它可以正常工作。如果我只是在不预编译的情况下运行此查询,它就可以正常工作。我在这里想念什么?