Get navigation properties in Entity Framework Core

c# entity-framework-core

Question

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?

1
7
1/3/2018 6:02:15 AM

Popular Answer

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)).

8
1/3/2018 9:42:09 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow