jeudi 19 février 2015

Include all navigation properties implementing interface type in Entity Framework's DbQuery

I have non-generic DbQuery and in order to optimize query I want to include all navigation properties with type implementing specific type. For the whole object graph, not only first level.


For a first level, I can propose my extension method:



public static DbQuery IncludeImplementors(this DbQuery dbq, Type typeToImplement)
{
var includedPropNames = dbq.ElementType
.GetProperties()
.Where(pi => pi.IsNavigationProperty() && typeToImplement.IsAssignableFrom(pi.PropertyType))
.Select(pi => pi.Name);

return includedPropNames.Aggregate(dbq, (current, propName) => current.Include(propName));
}


I assume, that implementing extension method bool IsNavigationProperty(this PropertyInfo pi) is trivial


Is there any recursion masters?






Aucun commentaire:

Enregistrer un commentaire