Search code examples
entity-framework-4properties

entity framework check if property is navigation property


Is there any way to see if property of an entity is navigation property, from its metadata?

I can determine if property is entity collection by inspecting if it implements ICollection and from there i can conclude if it is navigation property.

But what about if property is not entity collection but only reference to another entity?


Solution

  • You can get the O-Space EDM entity type from MetdataWorkspace and it has NavigationProperties property. Here is an example:

    var workspace = ((IObjectContextAdapter) ctx).ObjectContext.MetadataWorkspace;
    var itemCollection = (ObjectItemCollection)(workspace.GetItemCollection(DataSpace.OSpace));
    var entityType = itemCollection.OfType<EntityType>().Single(e => itemCollection.GetClrType(e) == typeof(MyEntity));
    foreach(var navigationProperty in entityType.NavigationProperties)
    {
        Console.WriteLine(navigationProperty.Name);
    }