Skip to main content

Generic Method for Class DB table mapping


·      Code for mapping db selection to the class

using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;

namespace DataSourceLib
{
    public class DataSource
    {
        private DataSource() { }
        public DataSource(DataSet data) {
            if (data == null) { data = new DataSet(); }
            dataSet = data;
        }
        private DataSet dataSet { set; get; }


        public IList<T> GetList<T>()
        {
            List<T> list = new List<T>();
            try
            {
                DataTable dt = dataSet.Tables[0];
                foreach (DataRow dr in dt.Rows)
                {
                    T obj = (T)Activator.CreateInstance(typeof(T));
                    PropertyInfo[] propertyInfos;
                    propertyInfos = obj.GetType().GetProperties();
                    for (int i = 0; i < dataSet.Tables[0].Columns.Count; i++)
                    {
                        foreach (PropertyInfo propertyInfo in propertyInfos)
                        {
if (dt.Columns[i].ColumnName.ToLower() ==   propertyInfo.Name.ToLower())
                            {
var val = Convert.ChangeType(dr[dt.Columns[i].ColumnName], propertyInfo.PropertyType);
                            propertyInfo.SetValue(obj, val);
                            }
                        }
                    }
                    list.Add(obj);
                }
            }
            catch (Exception)
            {
                T obj = (T)Activator.CreateInstance(typeof(T));
                list.Add(obj);
            }
            return list;
        }
    }
}

·       Client code
       class Program
    {
        static void Main()
        {
            string connectionString = GetConnectionString();
            DataSet dataSet = ConnectToData(connectionString);
            DataSourceLib.DataSource dataSource = new DataSourceLib.DataSource(dataSet);
            IList< User > users = dataSource.GetList< User >();

        }
    }
    public class User
    {
        public string ClientName { get; set; }
        public int ClientCode { get; set; }
    }


Comments

Popular posts from this blog

NHibernate Introduction

 NHibernate NHibernate is an open source Object-Relational Mapping (ORM) tool for the .Net platform… and the existing documentation and tutorials that I could find, whilst plentiful, are not aimed at those new to or inexperienced with ORM. This tutorial is based on using Visual Studio (I used 2008 beta 2) and Sql Server, however the database used is almost immaterial (one of the advantages of using an OR mapper). If you already know what NHibernate and ORM are and you want to use it but just need to know how?  Otherwise, read on. WTF is ORM? There is plenty of good stuff out there on what Object-Relational Mapping is, try wikipedia or the intro here (the tutorial is a bit out of date but the explanation is good) or there’s always Google . However, in a nutshell, ORM is the process of mapping business objects (think OOP) to database relations (read tables). An OR Mapper is a tool that manages this process. There are several different OR Mappers available for ...

NHibernate QueryOver Class And Projection....

Introduction The ICriteria API is NHibernate's implementation of Query Object . NHibernate 3.0 introduces the QueryOver api, which combines the use of Extension Methods and Lambda Expressions (both new in .Net 3.5) to provide a statically typesafe wrapper round the ICriteria API. QueryOver uses Lambda Expressions to provide some extra syntax to remove the 'magic strings' from your ICriteria queries. So, for example: .Add(Expression.Eq("Name", "Smith")) becomes: .Where<Person>(p => p.Name == "Smith") With this kind of syntax there are no 'magic strings', and refactoring tools like 'Find All References', and 'Refactor->Rename' work perfectly. Note: QueryOver is intended to remove the references to 'magic strings' from the ICriteria API while maintaining it's opaqueness. It is not a LINQ provider; NHibernate 3.0 has a built-in ...

Computer Science Defenition

Computer Science Computer science is the scientific and practical approach to computation and its applications. It is the systematic study of the feasibility, structure, expression, and mechanization of the methodical procedures (or algorithms ) that underlie the acquisition, representation, processing, storage, communication of, and access to information , whether such information is encoded as bits in a computer memory or transcribed in genes and protein structures in a biological cell . [1] A computer scientist specializes in the theory of computation and the design of computational system