Tips and Tricks in a world of Mix

   1: /// <summary>

   2:        /// Convert a single DataRow into an object of type T.

   3:        /// </summary>

   4:        /// <explanation>

   5:        /// where T : class, new() a constraint on the generic parameter. it must be a class (or reference type), 

   6:        /// and must have an parameterless default constructor.

   7:        /// </explanation>

   8:        public static T ConvertDataRowToEntity<T>(DataRow row) where T : class, new()

   9:        {

  10:            Type objType = typeof(T);

  11:            T obj = Activator.CreateInstance<T>(); //hence the new() contsraint of T object 

  12:            Debug.WriteLine(objType.Name + " = new " + objType.Name + "();");

  13:            foreach (DataColumn column in row.Table.Columns)

  14:            {

  15:                ///by column in the table we get the property in objType ignoring the unneeded ones

  16:                PropertyInfo property =  objType.GetProperty(column.ColumnName,   

  17:                    BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);

  18:                if (property == null || !property.CanWrite)

  19:                {

  20:                    Debug.WriteLine("//Property " + column.ColumnName + " not in object");

  21:                    continue; //or throw

  22:                }

  23:                //}

  24:  

  25:                ///in case the type of the property is different from data object type - 

  26:                ///convert it to the right type

  27:                object value = row[column.ColumnName];

  28:                if (value == DBNull.Value) value = null;

  29:                else

  30:                {

  31:                    Type propertyType = property.PropertyType;

  32:                    Type dataObjectType = row[column.ColumnName].GetType();

  33:                    if (propertyType.ToString() != dataObjectType.ToString())

  34:                    {

  35:                        value = Convert.ChangeType(value, propertyType);

  36:                    }

  37:                }

  38:                property.SetValue(obj, value, null);

  39:                Debug.WriteLine("obj." + property.Name + " = row[\"" + column.ColumnName + "\"];");

  40:            }

  41:            return obj;

  42:        }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Tag Cloud

%d bloggers like this: