advanced web statistics

Populate a List of SqlParameters using System.Reflection

6/28/2007 7:22:01 PM

I was messing around with Reflection again today in streamlining a Data Access Layer that I have been using.  The DAL currently in use isn`t very 2.0`ish so I figure I could start with making the command parameters easier to set. Using Reflection and simple string formatting I was able to take the Property Name and create a parameter out of it.  For example and proof-of-concept:

string property = "PropertyName";

Response.Write(string.Format("Property = {0}<br />", property)); // PropertyName

Response.Write(string.Format("Parameter = {0}<br />", property.Remove(0, 1).Insert(0, property.Substring(0, 1).ToLower()))); // propertyName

Basic Example Using System.Reflection

public static List<SqlParameter> Parameters(object input)
{
   Type t = input.GetType();
   List<SqlParameter> parameters = new List<SqlParameter>();

   foreach (PropertyInfo p in t.GetProperties())
      parameters.Add(new SqlParameter(p.Name.Remove(0, 1).Insert(0, p.Name.Substring(0, 1).ToLower()), p.GetValue(input, null)));

   return
parameters;
}

Pretty basic. A work in progress but I thought that I would share.  This will hopefully payoff in the long-run.

UPDATE
It has. And in a major way!

C#, Code

kick it on DotNetKicks.com

Leave a Comment

   

  Enter the text to proceed!