How can I retrieve all of an entity's property names?

c# entity-framework


What I'm trying to do is to pass an entity object to method and return all the names of the properties in it.
I'm using this code to get all the props names :

return classObject.GetType().GetProperties();

The problem is that this code return "EntityKey" and "EntityState" as properties whe I use it with Entity Object.
Is there any way to do it ?

Thanx in advance

5/1/2011 8:44:24 PM

Accepted Answer

You want all direct properties, but not the properties of the base type, which in your case is EntityObject:

var type = classObject.GetType();
//alternatively call out directly: typeof(EntityObject).GetProperties()...
var basePropertyNames = type.BaseType.GetProperties().Select(x => x.Name);
var props = type.GetProperties().Where(p => !basePropertyNames.Contains(p.Name));

This sample assumes there is a base type (which is the case for DB first), refactor when that is not guaranteed.

Edit from @Matt's comment: All of the above is unnecessary, could slap my head for not thinking of this - just use the right binding flags:

return classObject.GetType().GetProperties(BindingFlags.DeclaredOnly | 
                                           BindingFlags.Public | 
5/1/2011 9:04:48 PM

Popular Answer

It is also possible without reflection:

using (var context = new ModelContainer())
    // Access CSDL
    var container = context.MetadataWorkspace
                           .GetEntityContainer(context.DefaultContainerName, DataSpace.CSpace);
    // Access name of related set exposed on your context
    var set = container.BaseEntitySets[context.YourEntitySet.EntitySet.Name];
    // Access all properties
    var properties = set.ElementType.Members.Select(m => m.Name).ToList();
    // Access only keys
    var keys = set.ElementType.KeyMembers.Select(m => m.Name).ToList();

As you can see you have access to much more then names. The example shows that you can now which property is part of key. If you access Members directly you can know which property is scalar, complex type or navigation property.

All information are already loaded so there is no need for reflection. If you want to use reflection don't forget to use it only once (first time you need it) and then store and reuse received property names. Reflection is slow so using it each time you need names is a bad practice.

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow