C#: Code to load Object from Database


It is often when managing old project that do not use ORM coding, we need to load object from database. In such scenarios it is quite boring to code all 30-40 property to load from DB. So, I wrote this simple code which does it quite well for me, the only catch is you need to define object property same as their DB column name. So, here is the quick code for the same.

public void LoadRS(DataRow rs)
    {
        foreach (PropertyInfo propertyInfo in this.GetType().GetProperties())
        {
            try
            {
                if (propertyInfo.CanRead)
                {
                    if (rs.Table.Columns.Contains(propertyInfo.Name))
                    {
                        
                        switch (propertyInfo.PropertyType.Name)
                        {
                            case "String":
                                propertyInfo.SetValue(this, Convert.ToString(rs[propertyInfo.Name]), null);
                                break;
                            case "Int64":
                                propertyInfo.SetValue(this, long.Parse(Convert.ToString(rs[propertyInfo.Name])), null);
                                break;
                            case "Int32":
                                propertyInfo.SetValue(this, int.Parse(Convert.ToString(rs[propertyInfo.Name])), null);
                                break;
                            default:
                                propertyInfo.SetValue(this, Convert.ChangeType(Convert.ToString(rs[propertyInfo.Name]), propertyInfo.PropertyType), null);
                                break;
                        }
                    }
                }
            }
            catch { }
        }
    }

  The code use the System.Reflection and then it read the Object property [see this.GetType().GetProperties() in foreach], iterate over properties and then checking if DataRow contain the same name column, if so, it load them. Basically the Default statement in Switch is enough for most cases, but I still leave it as is insight that in future I might need to cast some particular DB field to other field here. Oh, yes that one condition is boolean field. 

There are lot of upgradation coming in my mind as I write this blog entry, but currently no time to upgrade it and will add this function in my class library for future use. 

,