Getting entity names from context in EF 4
I'd like to get all my entities' names from context and property names from entity. The second problem can be resolved using reflection but how to do the first part?
For example, I've got entities User
and Address
, each user has address. As result I need to get the following:
Entity: User
Property: LastName
Property: FirstName
Property: Address
Entity: Address
Property: City
Property: Street
To start, the entities (base type ComplexObject
) are actually distinct from the context, being housed in their own classes.
If you want to find all the entity types, you can use relfection to search the current assembly for any type that inherits ComplexObject
like so:
List<Type> Types = Assembly.GetExecutingAssembly().GetTypes().Where(T => T.IsSubclassOf(typeof(ComplexObject))).ToList();
Each of these types is defined with an EdmxComplexType
attribute, which gives you the namespace name and complex type name. You can get those attributes, for each type T
, like this:
T Instance_Of_T = (T)Activator.CreateInstance(T);
System.Data.Objects.DataClasses.EdmxComplexTypeAttribute complexTypeAttr = TypeDescriptor.GetAttributes(Instance_Of_T).OfType<System.Data.Objects.DataClasses.EdmxComplexTypeAttribute>().ToList().Single();
string NamespaceName = complexTypeAttr.NamespaceName;
string TypeName = complexTypeAttr.Name;
Hope that helps
精彩评论