0

I need to load the navigation property of an entity. I've been reading a great article on different approaches how to load navigation properties with Entity Framework (6.0).

The second way to explicitly Load is from the ObjectContext, rather than from EntityCollection or EntityReference. If you’re relying on POCO support in the Entity Framework, your navigation properties won’t be EntityCollections or EntityReferences, and therefore won’t have the Load method. Instead, you can use the ObjectContext.LoadProperty method. LoadProperty uses generics to identify the type that you’re loading from and then a lambda expression to specify which navigation property to load. Here’s an example of using LoadProperty to retrieve the Pets for a particular person instance:

context.LoadProperty<Family>(familyInstance, f => f.Pets)

Now the only thing I need to know:

How do I get a reference to the ObjectContext?

DbContext does not seem to derive from it, nor does it hold a reference to it. The LoadProperty<T> is not static, so I do need an object reference.

bas
  • 13,550
  • 20
  • 69
  • 146
  • possible duplicate of [Convert DBContext to ObjectContext for use with GridView](http://stackoverflow.com/questions/8059900/convert-dbcontext-to-objectcontext-for-use-with-gridview) – Gert Arnold Mar 02 '13 at 12:35
  • Yo thx a lot. Will delete the question. Sorry for the duplication. – bas Mar 02 '13 at 12:40

1 Answers1

1

There are 2 ways that I know of to load related collections with a DbContext.

One is the option you have asked about, but there is another way that I have been using for some time now and does not require a reference to ObjectContext. This method works from the DbEntityEntry collection. Here's an example:

public void Load<TEntity, TElement>(
        TEntity entity, 
        Expression<Func<TEntity, ICollection<TElement>>> relation)
    where TEntity : AbstractEntity, new()
    where TElement : AbstractEntity, new()
{
    var x = _context.Entry(entity);
    if (!x.State.Is(EntityState.Detached) && !x.State.Is(EntityState.Added))
        x.Collection(relation).Load();
}

or

public void Load<TEntity, TElement>(
        TEntity entity, 
        Expression<Func<TEntity, TElement>> relation)
    where TEntity : AbstractEntity, new()
    where TElement : AbstractEntity, new()
{
    var x = _context.Entry(entity);
    if (!x.State.Is(EntityState.Detached) && !x.State.Is(EntityState.Added))
        x.Reference(relation).Load();
}
qujck
  • 14,388
  • 4
  • 45
  • 74
  • 1
    Hmmmmm that is a nice alternative indeed. I could upvote and accept your question, the problem is that you 666 points! That's a damn shame isn't it ;-). Will un-satan you anyway. thx for the answer :) – bas Mar 02 '13 at 14:13
  • 1
    @bas yes it is a shame, but it couldn't last ;-) – qujck Mar 02 '13 at 14:34