2

Consider the following setup with models TodoItem and Person

modelBuilder.Entity<TodoItem>()
    .HasOne(t => t.Assignee)
    // for simplicity lets assume a Person is assigned to only TodoItem
    .WithOne(p => p.AssignedItem)
    .HasForeignKey(t => t.AssigneeId);

modelBuilder.Entity<TodoItem>()
    .HasOne(t => t.Reviewer)
    .WithOne(p => p.ReviewItem) 
    // for simplicity lets assume a Person owns only one TodoItem
    .HasForeignKey(t => t.ReviewerId);

reflectively, probably using Microsoft.EntityFrameworkCore.Metadata, how can I figure out that

  • the property TodoItem.Assignee (as configured in HasOne( ... ) ) is associated with the "inverse navigation property" Person.AssignedItem (as configured in in WithOne( ... )
  • and similarly, the property TodoItem.Reviewer is "inversely related" to Person.ReviewItem

I guess I'm trying to figure out how to access the configuration set in the modelBuilder.Hasxxx( ... ) and modelBuilder.Withxxx( ... ) methods.

I need this because I'm reflectively traversing through a query result set of a nested data structure and need to ensure that my algorithm is forward looking.

Maurits Moeys
  • 1,116
  • 1
  • 12
  • 22

1 Answers1

3

Navigations in the EF Core metadata are represented by INavigation interface. They can be obtained from IEntityType using GetNavigations or FindNavigation extension methods.

Once you have INavigation, the inverse navigation (if exists) can be obtained with FindInverse extension method.

You can see sample navigation traversal in my answer to Entity Framework Core 2.0.1 Eager Loading on all nested related entities.

Ivan Stoev
  • 195,425
  • 15
  • 312
  • 343