How can I find the Id property or properties related to a navigational property?

Vincent

For a project I'm working with Entity Framework and I'd like to be able to enumerate all navigational properties for a given object instance (assuming it's an object generated by EF). From there I'd like to get the related Id property for every navigational property.

For example, if I get an instance of the class Person, I want to be able to find it's navigational properties called Address and Boss. For those two navigational properties I want to then "lookup" the related Id properties called AddressId and BossId.

I need those Id properties so I can run queries on a different database which does not have the same foreign keys but does have exactly the same Ids.

So far I have figured out a way to get the RelationshipManager for a random object instance generated by EF. And while debugging I can get to the foreign key relations via the Manager's Relationships property. But I can only get as far as the navigational property name. So I can see there's a FK_Person_Address which is related to the navigational property called Address but I can't find the AddressId.

So my question is, how can I dynamically (with no knowledge of the Person class' layout) discover the AddressId property which is related to Address?

I am aware the Foreign Key relationship might have the Id property on the other side of the relation (Boss pointing to Person in stead of Person having a BossId). In that case, I'd still like to discover that Boss has a PersonId when I'm inspecting an instance of Person.

Penko

This will give you a dictionary with all navigation properties as Key and all related properties as Value (the value might be a property from the other entity)

Add these to your DBContext class and call db.GetForeignKeyProperties<Person>()

The result will be something like:

"Address" - "AddressID"

"Boss" - "Person.BossID"

public Dictionary<string,string> GetForeignKeyProperties<DBType>()
{
    EntityType table = GetTableEntityType<DBType>();
    Dictionary<string, string> foreignKeys = new Dictionary<string, string>();

    foreach (NavigationProperty np in table.NavigationProperties)
    {
        var association = (np.ToEndMember.DeclaringType as AssociationType);
        var constraint = association.ReferentialConstraints.FirstOrDefault();



        if (constraint != null && constraint.ToRole.GetEntityType() == table)
            foreignKeys.Add(np.Name, constraint.ToProperties.First().Name);

        if (constraint != null && constraint.FromRole.GetEntityType() == table)
            foreignKeys.Add(np.Name, constraint.ToProperties.First().DeclaringType.Name+"."+constraint.ToProperties.First().Name);
    }

    return foreignKeys;
}

private EntityType GetTableEntityType<DBType>()
{
    return GetTableEntityType(typeof(DBType));
}

private EntityType GetTableEntityType(Type DBType)
{
    ObjectContext objContext = ((IObjectContextAdapter)this).ObjectContext;
    MetadataWorkspace workspace = objContext.MetadataWorkspace;
    EntityType table = workspace.GetEdmSpaceType((StructuralType)workspace.GetItem<EntityType>(DBType.FullName, DataSpace.OSpace)) as EntityType;
    return table;
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Can't find single property and navigate related data without IQueryable all properties

In JPA, how would I find all of a type that has a property value and a ManyTomany related entity with a property value?

How can I reuse a property within application.properties?

Adapt navigational property using Mapster

BreezeJS - How remove a navigational property from its parent?

Can I reference another property in a properties file (use ${property})

How can I find the type of a property dynamically in swift (Reflection/Mirror)?

How can I find out if a dynamic property exists in C#

TS/JS How can I find an index of objects nested property?

WPF: How can I find the source of an inherited property value

How can I check if variable property named id?

How can I add a count property to objects with similar id in array

How to expose Foreign Key property to existing entity having navigational property using EF6 Code First

How can I access this property?

How can I fix Webpack related error: Cannot assign to read only property 'exports' of object '#<Object>'?

How to find if a set of objects share one property, which can be either of two properties?

Run Queries on Models without FK/Navigational Property

Entity Framework Include() returns null navigational property

IdentityRole Navigational Property Exception Using Entity Framework

Saving entity duplicates navigational property in database

How can I change which div is showing using navigational buttons?

Binding to properties does not update the related property

How can I read properties from an object which is a property from another object?

How can i fetch property from application-test.properties file in Java class?

How can I check if the array of objects have duplicate property values with more properties?

how can I bind properties of an object that is already a property of an already bound object?

In OSLC4J, how can I add a property to a Resource which has seven associated properties?

In TornadoFX, how can I make one Property change when other properties are changed?

how can i concatenate two properties into one property using hibernate criteria query

TOP Ranking

HotTag

Archive