I\'m working on creating a generic repository for an EF Core project to avoid having to write CRUD for all models. A major roadblock I\'ve hit is navigation properties not b
Working with metadata in EF Core is much easier than in previous EF versions. The DbContext class provides Model property which provides access to
The metadata about the shape of entities, the relationships between them, and how they map to the database.
The code which does what you ask could be like this:
public virtual IQueryable<T> Query(bool eager = false)
{
var query = _context.Set<T>().AsQueryable();
if (eager)
{
var navigations = _context.Model.FindEntityType(typeof(T))
.GetDerivedTypesInclusive()
.SelectMany(type => type.GetNavigations())
.Distinct();
foreach (var property in navigations)
query = query.Include(property.Name);
}
return query;
}
public virtual T Get(Guid itemId, bool eager = false)
{
return Query(eager).SingleOrDefault(i => i.EntityId == itemId);
}
Please note that although this does what you asked for, it's quite limited generic approach since it eager loads only the direct navigation properties of the entity, i.e. does not handle loading nested navigation properties with ThenInclude
.
private List<PropertyInfo> GetNavigationProperties<T>(GesFormaContext _gesFormaContext)
{
List<PropertyInfo> propertyInfos = new List<PropertyInfo>();
_gesFormaContext.Model.GetEntityTypes().Select(x => x.GetNavigations()).ToList().ForEach(entityTypes =>
{
entityTypes.ToList().ForEach(property =>
{
propertyInfos.AddRange(typeof(T).GetProperties().Where(x => x.PropertyType == property.PropertyInfo.PropertyType).ToList());
});
});
return propertyInfos;
}