Friday, 29 August 2014

Mapping DataSet with ASP.Net MVC Model

In ASP.Net MVC we suppose to use an Entity framework to deal with database part.

During same there is no issue with mapping a model with database table. Will use DbSet which map the appropriate columns a with model property.

But when we suppose to use plan ADO.Net classes or like a ORM lite libraries then there is a problem with mapping a database table with your model.

To deal with this specific situation I came with a following generic class which will map a DataSet with given model.

For the same use add following class into you project.

public static class CollectionExtensions
    {
        public static IList<T> ConvertTo<T>(this DataTable table)
        {
            if (table == null)
            {
                return null;
            }

            List<DataRow> rows = new List<DataRow>();

            foreach (DataRow row in table.Rows)
            {
                rows.Add(row);
            }

            return ConvertTo<T>(rows);
        }


        public static IList<T> ConvertTo<T>(IList<DataRow> rows)
        {
            IList<T> list = null;

            if (rows != null)
            {
                list = new List<T>();

                foreach (DataRow row in rows)
                {
                    T item = CreateItem<T>(row);
                    list.Add(item);
                }
            }

            return list;
        }

        public static T CreateItem<T>(this DataRow row)
        {
            T obj = default(T);
            if (row != null)
            {
                obj = Activator.CreateInstance<T>();

                foreach (DataColumn column in row.Table.Columns)
                {
                    PropertyInfo prop = obj.GetType().GetProperty(column.ColumnName);
                    try
                    {
                        object value = row[column.ColumnName];
                        if (value != DBNull.Value)
                        {
                            prop.SetValue(obj, value, null);
                        }
                    }
                    catch
                    {
                        // You can log something here
                        throw;
                    }
                }
            }
            return obj;
        }
    }

To access above method into you controller you need to write following line of code which return your model type.

e.g: To map a single row

     DataSet dbSet = "select * from customer  where custmername = 'abc' ";

     Customer objCustomer = dbSet.Table[0].Rows[0].CreateItem<Customer>();

     This code will take a datarow and map it with your Customer model.


e.g: To map a multiple row

     DataSet dbSet = "select * from customer";

     List<Customer> objCustomer = dbSet.Table[0].ConvertTo<Customer>();

     This code will take a List of datarow and map it to your list of Customer model.



No comments:

Post a Comment