|
Reflection and EntityObjects
Published: 5/12/2009 |
|
In working with the Linq to Entity Framework I recently ran into the requirement to hide the delete button on a GridView if the item being displayed had any relationships with any other item in the database. I came up with a generic extension method that adds a "HasRelationships" method to every EntityObject in my UI program, it uses Reflection to query the properties of the underlying object to see if any relationships are set. Here it is:
C#
public static bool HasRelationships(this System.Data.Objects.DataClasses.EntityObject Item)
{
bool ret = false;
// look for relationship properties - by default disable if any relationships...
foreach (PropertyInfo property in Item.GetType().GetProperties())
{
if (!ret) // only keep looking if there isn't already a relationship...
{
if (property.PropertyType.IsSubclassOf(typeof(EntityReference)))
{
// get instance of object...
EntityReference Ref = property.GetGetMethod().Invoke(Item, null) as EntityReference;
// check for reference...
if (Ref.EntityKey != null) ret = true; // entity has a single reference property that is not null...
}
else if (property.PropertyType.GetInterface("System.ComponentModel.IListSource") != null)
{
// get instance of object...
object Ref = property.GetGetMethod().Invoke(Item, null);
// load items...
((IRelatedEnd)Ref).Load();
// count items...
PropertyInfo countProperty = Ref.GetType().GetProperty("Count");
if (countProperty != null)
{
if (((int)countProperty.GetGetMethod().Invoke(Ref, null)) > 0)
ret = true; // entity has a collection-type reference property with more than one item...
}
}
}
}
// optional TODO: handle type-specific results to override results...
// return default...
return ret;
}
Questions or Comments? .
VB to C# and C# to VB translation provided by Instant C# and Instant VB.