EntityException thrown executing EF6 query with .Includes()

c# entity-framework entity-framework-6

Question

I am having trouble migrating an EF4 solution to EF6.

We use T4 templates to generate persistent ignorant POCOs that have navigation properties based on ObservableCollection< T>.

Because our ObjectContext implementation exposes entity sets as IObjectSet< entity> we lose the Include() method from ObjectQuery and so have to use an extension method on IQueryable to regain it, as follows:

public static IQueryable<TSource> Include<TSource>(this IQueryable<TSource> source, string path)
{
    IQueryable<TSource> returnValue = source;
    var objectQuery = source as ObjectQuery<TSource>;

    if (objectQuery != null)
    {
        returnValue = objectQuery.Include(path);
    }

    return returnValue;
}

Having updated the solution to use EF6 we now see the following System.Data.Entity.Core.EntityException when executing queries using .Include() :-

"The navigation property 'Details' on entity of type 'DataEntities.Parent' must implement ICollection< T> in order for Entity Framework to be able to track changes in collections."

What I don't get is the 'Details' property is a custom type that inherits ObservableCollection< T> which is an ICollection< T>, so why the exception that states it must implement ICollection< T>?

If anyone has any light to shed on this I would be grateful, thanks.

Popular Answer

As explained in this blogpost of an EF team member

The rules that your classes must follow to enable change-tracking proxies are quite strict and restrictive. This limits how you can define your entities and prevents the use of things like private properties or even private setters.

The rules are:

  • The class must be public and not sealed.
  • All properties must have public/protected virtual getters and setters.
  • Collection navigation properties must be declared as ICollection. They cannot be IList, List, HashSet, and so on.

And this answer for an explanation why you can't use your implementation.




Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why