Here The Code By Using Which We Can Create a list from reader in C# ASP.net
public List<T> SelectAll(string constr, string table, object val)
{
List<T> list = new List<T>();
try
{
SqlConnection conn = Tools.GetConnection(constr);
IDbCommand command = Tools.GetSelectCommand(table, conn, "id", val);
IDataReader reader = command.ExecuteReader();
list = Cbo.FillCollection<T>(reader);
constr.cloase();
}
catch (Exception)
{
throw;
}
return list;
}
public static List<T> FillCollection<T>(IDataReader dr)
{
List<T> objFillCollection = new List<T>();
T objFillObject;
while (dr.Read())
{
// fill business object
objFillObject = CreateObject<T>(dr);
// add to collection
objFillCollection.Add(objFillObject);
}
if (!(dr == null))
{
dr.Close();
}
return objFillCollection;
}
private static T CreateObject<T>(IDataReader dr)
{
Type objType = null;
T obj = Activator.CreateInstance<T>();
List<PropertyInfo> properties = Helper.GetPropertyInfo(typeof(T));
int i;
for (i = 0; i < dr.FieldCount; i++)
{
string columnName = dr.GetName(i);
//now find matching property
PropertyInfo propMatch = properties.Find(delegate(PropertyInfo p)
{
Type t = typeof(T);
PropertyInfo pi = t.GetProperty(p.Name);
Column[] atrb = pi.GetCustomAttributes(typeof(Column), false) as Column[];
if (atrb != null)
{
if (atrb.Length > 0)
{
foreach (Column at in atrb)
if (at != null && !string.IsNullOrEmpty(at.Name))
{
return at.Name.ToLower() == columnName.ToLower();
}
}
}
return p.Name.ToLower() == columnName.ToLower();
});
if (propMatch != null)
{
//we have found a matching property. fill it in
if (Convert.IsDBNull(dr.GetValue(i)))
{
propMatch.SetValue(obj, Null.GetNull(propMatch), null);
}
else
{
try
{
// try implicit conversion first
propMatch.SetValue(obj, dr.GetValue(i), null);
}
catch
{
try
{
objType = propMatch.PropertyType;
// need to handle enumeration conversions differently than other base types
if (objType.BaseType.Equals(typeof(System.Enum)))
{
if (Helper.IsNumeric(dr.GetValue(i)))
{
propMatch.SetValue(obj, System.Enum.ToObject(objType, Convert.ToInt32(dr.GetValue(i))), null);
}
else
{
propMatch.SetValue(obj, System.Enum.ToObject(objType, dr.GetValue(i)), null);
}
}
else
{
propMatch.SetValue(obj, Convert.ChangeType(dr.GetValue(i), objType), null);
}
}
catch
{
propMatch.SetValue(obj, Convert.ChangeType(dr.GetValue(i), objType), null);
}
}
}
}
else
{
Console.WriteLine("property not found {0}", typeof(T).Name);
}
}
return obj;
}
No comments:
Post a Comment