I am attempting to perform the LoadProperty operation from my context to load a navigation property of a navigation property.
My setup is that I have an EntityA, which contains a list of EntityB’s, and each EntityB contains a list of EntityC’s. I am doing the following programatically:
public virtual List<T> LoadProperty(List<T> entities, string property)
{
using (MyContext context = new MyContext())
foreach (T entity in entities)
{
context.AttachTo(typeof(T).Name, entity);
context.LoadProperty(entity, property);
}
return entities;
}
I call it as such:
LoadProperty(entityA, "EntityB.EntityC");
I know that the NavigationProperty path is correct, however, this is not working. Is there a way to get this to load?
Edit:
Working example using Includes:
using (MyContext context = new MyContext())
{
var query = from entityA in context.EntityA.Include("EntityB").Include("EntityB.EntityC")
where entityA.Id == id
select entityA;
return query.ToList();
}
First off, your method call context.AttachTo(typeof(T).Name, entity) is not correct and you’ll get an InvalidOperationException. ObjectContext.AttachTo Method shows:
So we need to pass the EntitySet name and not the Entity name itself. But the good news is we can get the EntitySet name from MetadataWorkspace by having the Entity name. The code below shows how.
Now if you have 3 levels of object composition and EntityB and EntityC are navigation properties of type EntityCollections, then I don’t think you could load them both with one call to LoadProperty, but you can do it by call LoadProperty twice, here is how it can be done:
And you will call it:
This way you will have the full object graph constructed.