Entity Framework - Load entities with child entity
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 开发者_StackOverflow社区it?
The problem is that IQueryable
is agnostic of what's backing it, and Include
is an Entity Framework feature. You could have an IQueryable
that uses LINQ to Objects instead, and Include
wouldn't make sense there. The easiest thing would be to change the type of All()
to an IObjectSet
, from which you should have access to an Include
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.
IList<Parent> parentsWithEagerLoadedChildren = parentRepo.All()
.Select(p => new {p, p.Children}).ToList() // EF will attach the children to each parent
.Select(p => p.p).ToList(); // Now that everything is loaded, select just the parents
You can create your own extension method which will allow you to use Include(path)
against any IQueryable<T>
:
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;
}
There's a full explanation on Julie Lerman's blog: http://thedatafarm.com/blog/data-access/agile-entity-framework-4-repository-part-5-iobjectset/
精彩评论