Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 611
Milos Mijatovic Avatar asked Apr 20 '12 18:04

Milos Mijatovic


2 Answers

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);
}
like image 142
Pawel Avatar answered Oct 09 '22 12:10

Pawel


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();
    }
}
like image 28
GlTech Avatar answered Oct 09 '22 11:10

GlTech