In EF6, this method works to retrieve an entity's navigation properties:
private List<PropertyInfo> GetNavigationProperties<T>(DbContext context) where T : class
{
var entityType = typeof(T);
var elementType = ((IObjectContextAdapter)context).ObjectContext.CreateObjectSet<T>().EntitySet.ElementType;
return elementType.NavigationProperties.Select(property => entityType.GetProperty(property.Name)).ToList();
}
IObjectContextAdapter
however does not exist in EF Core. Where should I be looking to get the list of navigation properties of an entity?
You can explicitly load a navigation property via the DbContext. Entry(...) API. You can also explicitly load a navigation property by executing a separate query that returns the related entities.
A navigation property is an optional property on an entity type that allows for navigation from one end of an association to the other end. Unlike other properties, navigation properties do not carry data.
Reference navigation property: A navigation property that holds a reference to a single related entity. Inverse navigation property: When discussing a particular navigation property, this term refers to the navigation property on the other end of the relationship.
The DbContext class has a method called OnModelCreating that takes an instance of ModelBuilder as a parameter. This method is called by the framework when your context is first created to build the model and its mappings in memory.
Fortunately, access to the model data has become a lot easier in Entity Framework core. This is a way to list entity type names and their navigation property infos:
using Microsoft.EntityFrameworkCore;
...
var modelData = db.Model.GetEntityTypes()
.Select(t => new
{
t.ClrType.Name,
NavigationProperties = t.GetNavigations().Select(x => x.PropertyInfo)
});
... where db
is a context instance.
You would probably like to use the overload GetEntityTypes(typeof(T))
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With