Lei Yang Lei Yang - 4 months ago 19
C# Question

Get Navigation Properties of given EntityType

I am using VS2010, EF4.0. Need function like the following.

private string[] GetNaviProps(Type entityType)//eg typeof(Employee)
{
NorthwindEntities en = new NorthwindEntities();
//here I return all Properties only for example
return entityType.GetProperties().Select(p=>p.Name).ToArray();
//should return Orders,Territories...
}


I have checked this, but IObjectContextAdapter seems something in EF6.0 and .net4.5. I tried to replace it like

var workspace = en.MetadataWorkspace;


So it can compile, but exception throw at the 3nd line then.

Any help?

Answer

You can filter GetProperties results to get only these which implement ICollection or IEnumerable. However, you should remember that string implements IEnumerable, so you have to add additional check not to return string properties.

return entityType.GetProperties()
                 .Where(p => typeof(IEnumerable).IsAssignableFrom(p.PropertyType) && p.PropertyType != string)
                 .Select(p => p.Name)
                 .ToArray();

Update

You can change you Where predicate to compare namespaces as well. It returns also 1:1 navigation properties:

private static string[] GetNaviProps(Type entityType)//eg typeof(Employee)
{
    return entityType.GetProperties()
                     .Where(p => (typeof(IEnumerable).IsAssignableFrom(p.PropertyType) && p.PropertyType != typeof(string)) ||  p.PropertyType.Namespace == entityType.Namespace)
                     .Select(p => p.Name)
                     .ToArray();
}