entity framework check if property is navigation p

2020-02-10 08:45发布

问题:

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?

回答1:

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);
}


回答2:

You can use one more approach to solve the problem.

Obs: found variable is some DbContext entity instance;

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

    if (reference != null)
    {
        reference.Load();
    }
}