This article describes filling a "Data class" using a generic method. Reflection is used to find the property of any passed class dynamically and assign the value. The below approach will be very userful in large applications where hundreds of classes have to be filled throughout the flow.
Consider you have a data class called "Person" which contains below listed properties
{Name, Address, City, State, Country} . If this data object has to be filled the usual way is to get a datareader or dataset and assign the values directly.
But this new strategy iterates through each and every property of any passed object and assigns value from datareader automatically.
UI
- Person person = new Person();
- DAL dal = new DAL();
-
- dal.ExecuteDataReader(person, "a");
- Response.Write("Name: " + person.Name + "<br>");
- Response.Write("Address: " + person.Address + "<br>");
- Response.Write("City: " + person.City + "<br>");
- Response.Write("State: " + person.State + "<br>");
- Response.Write("Country: " + person.Country + "<br>");
DAL
-
-
-
-
-
-
- public void ExecuteClass(object objectClass, string parameter1)
- {
- try
- {
- sqlConnection = new SqlConnection(@"Server=SridharDEV;Database=EntLibTest;Uid=Test;Pwd=Test;");
- sqlConnection.Open();
- sqlCommand = new SqlCommand("SELECT * FROM PERSON WHERE NAME='" + parameter1 + "'", sqlConnection);
- sqlDataReader = sqlCommand.ExecuteReader();
- Type theType = objectClass.GetType();
- PropertyInfo[] p = theType.GetProperties();
- object[] custAttr = null;
- while (sqlDataReader.Read())
- {
- foreach (PropertyInfo pi in p)
- {
- try
- {
- custAttr = pi.GetCustomAttributes(true);
- if ((sqlDataReader[pi.Name] != System.DBNull.Value) && (custAttr.Length == 0))
- pi.SetValue(objectClass, sqlDataReader[pi.Name], null);
- }
- catch (System.IndexOutOfRangeException) { }
- }
- }
- }
- catch (Exception ex)
- {
- throw ex;
- }
- finally
- {
- if (sqlDataReader.IsClosed == false)
- sqlDataReader.Close();
- if (sqlConnection.State == ConnectionState.Open)
- sqlConnection.Close();
- sqlConnection.Dispose();
- }
- }