Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 479
Guerrilla Avatar asked Jan 03 '18 03:01

Guerrilla


People also ask

How do I load navigation properties in Entity Framework Core?

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.

What are navigation properties in Entity Framework?

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.

What is reference navigation property?

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.

What is OnModelCreating in Entity Framework?

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.


1 Answers

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

like image 180
Gert Arnold Avatar answered Sep 20 '22 21:09

Gert Arnold