'Get navigation properties in Entity Framework Core
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?
Solution 1:[1]
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))
.
Solution 2:[2]
EF core 6+
This works for me:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Fare>().Navigation(f => f.Extras).AutoInclude();
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Sampath |