jump to navigation

Using reflection to copy a DataRow to a class September 14, 2007

Posted by codinglifestyle in ASP.NET, C#.
Tags: , , , ,
trackback

Very often when working with DB tables we serialize a row in to class.  This entity class simply holds the data and hosts a rack of get and set methods.  The data layer serializes this class, the business logic layer manipulated it, and the UI layer ultimately displays it.  Here is a simple example:

 

    class Class1

    {

        private string m_sProp1;

        private int m_nProp2;

 

        public string Prop1

        {

            get

            {

                return m_sProp1;

            }

            set

            {

                m_sProp1 = value;

            }

        }

 

        public int Prop2

        {

            get

            {

                return m_nProp2;

            }

            set

            {

                m_nProp2 = value;

            }

        }

    }

 

Very often somewhere in the UI and/or logic layers you have a large function laboriously copying each value in or out of the entity class.  In my case, I was serializing the entity to a DataSet to be displayed in a Repeater control.  So I thought to myself, “Self, wouldn’t it be cool to use reflection to automatically perform the copy”.  While I didn’t know much about reflection a couple hours ago, it’s remarkably easy to use and, as you probably know, very powerful.  Let’s get started…

 

I need a copy function to copy a DataRow to my entity class and vice versa.  We’ll address the first case. 

 

        public static object SetValuesToObject(Type tClass, DataRow dr)

        {

            try

            {

                Object oClass        = System.Activator.CreateInstance(tClass);

                MemberInfo[] methods = tClass.GetMethods();

                ArrayList aMethods   = new ArrayList();

                object[] aoParam     = new object[1];

 

                //Get simple SET methods

                foreach (MethodInfo method in methods)

                {

                    if (method.DeclaringType == tClass && method.Name.StartsWith(“set_”))

                        aMethods.Add(method);

                }

 

                //Invoke each set method with mapped value

                for (int i = 0; i < aMethods.Count; i++)

                {

                    try

                    {

                        MethodInfo mInvoke = (MethodInfo)aMethods[i];

                        //Remove “set_” from method name

                        string sColumn = mInvoke.Name.Remove(0, 4);

                        //If row contains value for method…

                        if (dr.Table.Columns.Contains(sColumn))

                        {

                            //Get the parameter (always one for a set property)

                            ParameterInfo[] api = mInvoke.GetParameters();

                            ParameterInfo   pi  = api[0]; 

 

                            //Convert value to parameter type

                            aoParam[0] = Convert.ChangeType(dr[sColumn], pi.ParameterType);

                           

                            //Invoke the method

                            mInvoke.Invoke(oClass, aoParam);

                        }

                    }

                    catch

                    {

                        System.Diagnostics.Debug.Assert(false, “SetValuesToObject failed to set a value to an object”);

                    }

                }

                return oClass;

            }

            catch

            {

                System.Diagnostics.Debug.Assert(false, “SetValuesToObject failed to create an object”);

                return null;

            }

        } 



The way this works is I’m going to pass in a Type and a DataRow.  First we look through at all the methods in the entity class and pull out all the set methods.  Then look at the DataRow to see if we have a column which corresponds to the method.  Looking at the example entity class above, I would be hoping to have a column called Prop1 and Prop2*.  We the look to see what type of set method is expecting: string, int, DateTime, ect.  We use this to convert the value from the DataRow and set this in to an object array of length 1.  Finally, invoke the set method passing in the object array.  The end result, a newly instantiated entity class pre-populated with the values from the DataRow.

 

* Although it’s rare to abide by a naming convention in reality, this is new code, so we will keep naming identical from DB to entity to DataTable.  It would be trivial to introduce a mapping of column to property.

 

Advertisements

Comments»

No comments yet — be the first.

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

%d bloggers like this: