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

c# entity-framework

Question


I want to provide a method an entity object and have it return all the names of the attributes it has.
To retrieve the names of all the properties, I'm using this code:

return classObject.GetType().GetProperties();

The issue is that when I use this code with an entity object, "EntityKey" and "EntityState" are returned as properties.
Is there a way to do it?

I appreciate you.

1
9
5/1/2011 8:44:24 PM

Accepted Answer

You want the basic type's attributes but not its direct counterparts, which in your situation isEntityObject :

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 example refactors when the existence of a base type is not guaranteed (which is the situation for DB first).

From @Matt's remark, Edit Use the appropriate binding flags instead of doing all of the above; I could smack myself for not thinking of this.

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

Popular Answer

In addition, without contemplation:

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, your options go well beyond names. The example demonstrates how you may identify which property is a component of the key. If you visitMembers Which property is a scalar, complex type, or navigation property may be determined immediately.

There is no need for reflection since all the information is already loaded. Remember to only utilize reflection the first time you need it, then save and reuse the property names you obtain. Using reflection every time you require names is a terrible idea since it takes time.



Related Questions





Related

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