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?
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();
}
I know I'm a little late to the party, but you can use the Entity Framework way to retrieve the navigation properties instead of using reflection:
MetadataWorkspace workspace = ((IObjectContextAdapter)this.Context).ObjectContext.MetadataWorkspace;
ObjectItemCollection itemCollection = (ObjectItemCollection)(workspace.GetItemCollection(DataSpace.OSpace));
EntityType entityType = itemCollection.OfType<EntityType>().Single(e => itemCollection.GetClrType(e) == typeof(TEntity));
where this.Context
is an instance of the DbContext
class. After that you can access the EntityType's NavigationProperties property.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With