Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading