Entity Framework - Include / Reference / Collection

Simon picture Simon · Aug 6, 2013 · Viewed 16.2k times · Source

I was wondering why there are separate methods for populating navigation properties.

If I work on an entire set, i can call Include on either a property or a collection.

However, if I work on a single entity, there are two separate methods to call depending on whether the item is a collection (Collection) or single reference (Reference).

Is there any way around this - this is making things more complicated than I think is necessary. And could anyone explain why this was decided during designing EF?

EDIT

Looking into it further, the problem goes deeper. What I was trying to do is create a generic way to load collection/navigation properties on a single entity. This can be done easy enough on the whole set using Include. But the method signatures for Reference and Collection are slightly different.

Never mind, will have to scatter these calls around my app.

e.g.

dbSet<T>().Include(e => e.Property).Include(e => e.Collection).Include(e => e.Collection.Property) 

all seem to work.

However the calls for the single entity are different:

context.Entry(entity).Reference(e => e.Property).Load();
context.Entry(entity).Reference(e => e.Property.Select(e => e.SubProperty)).Load();
context.Entry(entity).Collection(e => e.Collection).Load();

Answer

haim770 picture haim770 · Aug 6, 2013

The only purpose of the Include() method is to explicitly eager load related data upon querying.

The Entry() method - on the other hand - is intended to give you specific control over the current state of an Entity attached to the context and not only Load() related data.

That is the reason why you have to explicitly choose between Collection, Reference and Property methods, each one exposes different set of functionality (hence returns different type).

For example:

  • Scalar (DbPropertyEntry) contains the IsModified property that denotes whether the value changed from 'x' to 'y' (for example).

  • Reference (DbReferenceEntry) contains the IsLoaded property that denotes whether the referenced data has been loaded from the database already.

  • Reference Collection (DbCollectionEntry) derives from ICollection (hence IEnumberable as well) which means that you can iterate over its data. Yet, it cannot contain an IsModified property because it may differ for each item in the collection.

Still, if you're only interested in Load(), you can leverage the polymorphic Member() method (that returns DbMemberEntry that is the base type to all of the above types) and check if the entry is "Loadable":

var memberEntry = this.Entry(entity).Member("NavigationProperty");

if (memberEntry is DbCollectionEntry collectionMember)
    collectionMember.Load();

if (memberEntry is DbReferenceEntry referenceMember)
    referenceMember.Load();