实体框架 - 使用子实体加载实体
我正在尝试的是将数据库中的所有 A 实体与 B 实体一起加载。它们之间的关系是每个A实体都有一个B实体。
我正在开发的项目有一个存储库模式,它有一个 All() 方法,如下所示。
public class EFRepository<T> : IRepository<T> where T : class, IObjectWithChangeTracker
{
private IObjectSet<T> objectset;
private IObjectSet<T> ObjectSet
{
get
{
if (objectset == null)
{
objectset = UnitOfWork.Context.GetObjectSet<T>();
}
return objectset;
}
}
public virtual IQueryable<T> All()
{
return ObjectSet.AsQueryable();
}
}
有什么方法可以强制 B 实体急切加载。我发现 IQueryable 上没有从 All() 方法返回的 Include 方法。我很高兴向存储库添加一个新成员,以便它可以允许客户端使用预加载。但我该怎么办呢?
What I am trying is to load all the A entities in the database together with B entities. The relationship between them is Every A entitiy has one B entitiy.
The project I am working on has a repository pattern and it has an All() method as below.
public class EFRepository<T> : IRepository<T> where T : class, IObjectWithChangeTracker
{
private IObjectSet<T> objectset;
private IObjectSet<T> ObjectSet
{
get
{
if (objectset == null)
{
objectset = UnitOfWork.Context.GetObjectSet<T>();
}
return objectset;
}
}
public virtual IQueryable<T> All()
{
return ObjectSet.AsQueryable();
}
}
Is there any way that I can force B entities to eager load. What I've found is there there is no Include method on the IQueryable that returns from the All() method. I am happy to add a new member to repositroy so it can allow the client to use eager loading. But how can I do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
发布评论
评论(2)
您可以创建自己的扩展方法,该方法将允许您对任何 IQueryable
使用 Include(path)
:
public static IQueryable<TSource> Include<TSource>
(this IQueryable<TSource> source, string path)
{
var objectQuery = source as ObjectQuery<TSource>;
if (objectQuery != null)
{
return objectQuery.Include(path);
}
return source;
}
Julie Lerman 的博客上有完整的解释:http://thedatafarm.com/blog/data-access/agile-entity-framework-4-repository-part-5-iobjectset/
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
问题在于,
IQueryable
不知道支持它的内容,而Include
是一个实体框架功能。您可以有一个使用 LINQ to Objects 的IQueryable
来代替,而Include
在那里没有意义。最简单的方法是将All()
的类型更改为IObjectSet
,从中您应该可以访问Include
扩展方法。如果您无法更改
All
的返回类型,则必须以能够急切地拉入子元素的方式构建查询。The problem is that
IQueryable
is agnostic of what's backing it, andInclude
is an Entity Framework feature. You could have anIQueryable
that uses LINQ to Objects instead, andInclude
wouldn't make sense there. The easiest thing would be to change the type ofAll()
to anIObjectSet
, from which you should have access to anInclude
extension method.If you can't change the return type of
All
, you will have to structure your queries in such a way that they pull in the child elements eagerly.