Search code examples
c#entity-framework-coremany-to-many

How can I determine whether a db entry's collection is part of a many-to-many relationship?


When looping through members of a Db entry, I would like to determine whether or not a particular navigation is part of a many-to-many relationship

When debugging, I can see a property collection.Metadata.ManyToManyLoader:

enter image description here

Which only seems to appear on my many-to-many collections

However, I can't seem to target or select that property in my code:

var test = collection.Metadata["ManyToManyLoader"];
var test2 = collection.Metadata.FindAnnotation("ManyToManyLoader");

Both test and test2 above are just null, even though I can see they shouldn't be in my locals tab

What gives?

Some more code:

var entry = DbContext.Entry(entity);

foreach (var collection in entry.Collections)
{
    var test = collection.Metadata["ManyToManyLoader"];
    var test2 = collection.Metadata.FindAnnotation("ManyToManyLoader");
}

Solution

  • Starting with EF Core 5.0, the Metadata property of collection entry is INavigationBase. Which could be actually either INavigation (for "regular" collection navigations) or ISkipNavigation (for skip navigations currently used for implicit many-to-many relationships).

    Hence you could check for that interface, e.g.

    if (collection.Metadata is ISkipNavigation info)
    {
        // some additional info if needed
        var declaringEntityType = info.DeclaringEntityType; // the entity containing the navigation
        var targetEntityType = info.TargetEntityType; // "other side" entity
        var joinEntityType = info.JoinEntityType; // join entity
        var foreignKey = info.ForeignKey; // foreign key of join entity to this entity
        var inverse = info.Inverse; // the navigation property of the "other side" entity
    }
    

    etc.