9

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?

2 Answers 2

11

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

Sign up to request clarification or add additional context in comments.

2 Comments

Or more precisely, FindEntityType(typeof(T)). HNY!
I think it is worth pointing out that the EF Core team has said that FindEntityType(Type) is not recommended to be used directly in your code because it could change. Here's a link
0

EF core 6+

This works for me:

protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Fare>().Navigation(f => f.Extras).AutoInclude(); } 

Ref: https://learn.microsoft.com/en-us/ef/core/querying/related-data/eager#model-configuration-for-auto-including-navigations

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.