Free Information Technology Magazines and eBooks

Monday, February 16, 2009

C#: Database to C# Class Wrapper

I had an VB .NET code class that connects and populates my collection class with all the records from my database. I decided to convert it to C# code to help our C# programmers to use it as class wrapper. The class also automatically detects and populate all class property values with its database field counterpart. It uses interface IDataRecord to accept a record, and PropertyInfo to check what property the database field value should go to. The caveat with this method is you must have to name your property exactly same as your database field name. Here's the code that loop over the database fields and decides what property it will be store into.

Type myProperties;
myProperties = this.GetType();

foreach (PropertyInfo pi in myProperties.GetProperties())
{
strDebugPropName = pi.Name;
if (pi.CanWrite && pi.Name.Substring(pi.Name.Length - 1) != "_")
{
switch (pi.PropertyType.ToString())
{
case "System.String":
pi.SetValue(this, TokenSTR(drRec.GetValue(drRec.GetOrdinal(pi.Name))), null);
break;
case "System.DateTime":
pi.SetValue(this, Convert.ToDateTime(drRec.GetValue(drRec.GetOrdinal(pi.Name)).ToString()), null);
break;
case "System.Single":
pi.SetValue(this, Convert.ToSingle(drRec.GetValue(drRec.GetOrdinal(pi.Name)).ToString()), null);
break;
case "System.Int32":
pi.SetValue(this, Convert.ToInt32(drRec.GetValue(drRec.GetOrdinal(pi.Name)).ToString()), null);
break;
default:
break;
}
}
}


For the complete code of the class, you can get it here



0 comments: