Entity framework checks if a property is a navigation property

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

I can determine if the property is an entity by checking if it implements ICollection, and from there I can conclude that this is a navigation property.

But what about the fact that the property is not a collection of entities, but only a reference to another object?

+3
source share
2 answers

You can get the O-Space EDM entity type from MetdataWorkspace and have the 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);
}
+5
source

You can use another approach to solving the problem.

// - DbContext;

foreach (var propertyInfo in found.GetType().GetProperties())
{
  var reference = Context.Entry(found).Member(propertyInfo.Name) as DbReferenceEntry;
  if(reference != null)
    reference.Load();
}

, .

+1

All Articles