Access deep object graph properties by string with LLBGen

PDF form and template-based emails often require accessing property values deep within an object graph. For example, in my current project the first name property of an employee is accessed via Employee.Person.FirstName.

The following method takes an object path as a string (such as "Employee.Person.Address.Line1") and, using recursion, returns its property value no matter how deep within the graph the desired property exists.

private static string GetObjectFromPath(string objectPath, EntityBase2 currentEntity)
{
   string[] parts = objectPath.Split('.');
   string firstPath = null;
   object propertyValue = null;

   if
(parts.Length > 0)
   {
      firstPath = parts[0];

      PropertyInfo
prop = currentEntity.GetType().GetProperty(firstPath);
      if (prop != null)
      {
         propertyValue = prop.GetValue(currentEntity,
null);
      }

      if
(propertyValue is EntityBase2)
      {
         objectPath = objectPath.Replace(firstPath +
".", "");
         return GetObjectFromPath(objectPath, propertyValue as EntityBase2);
      }
   }

   if (propertyValue == null)
   {
      return null;
   }
   return propertyValue.ToString();
}

Print | posted @ Monday, August 20, 2007 3:22 AM

Comments on this entry:

No comments posted yet.

Your comment:

Title:
Name:
Email:
Website:
 
Italic Underline Blockquote Hyperlink
 
 
Please add 5 and 6 and type the answer here: