·
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
Post a Comment