#region SqlDataReader to IList<T>
public static IList<T> SqlDataReaderToIList<T>(SqlDataReader sqldatareader)
{
try
{
IList<T> list = new List<T>();
while (sqldatareader.Read())
{
T t = System.Activator.CreateInstance<T>();
Type type = t.GetType();
for (int i = 0; i < sqldatareader.FieldCount; i++)
{
object TempValue = null;
if (sqldatareader.IsDBNull(i))
{
string typeFullName = type.GetProperty(sqldatareader.GetName(i)).PropertyType.FullName;
TempValue = GetDbNullValue(typeFullName);
}
else
{
TempValue = sqldatareader.GetValue(i);
}
type.GetProperty(sqldatareader.GetName(i)).SetValue(t, TempValue, null);
}
list.Add(t);
}
return list;
}
catch (Exception ex)
{
throw ex;
}
finally
{
sqldatareader.Close();
sqldatareader.Dispose();
}
}
private static object GetDbNullValue(string typeFullName)
{
typeFullName = typeFullName.ToLower();
if (typeFullName == "string")
return string.Empty;
else if (typeFullName == "int32" || typeFullName == "int16" || typeFullName == "int64")
return 0;
else if (typeFullName == "datetime")
return Convert.ToDateTime(DateTime.MinValue);
else if (typeFullName == "boolean")
return false;
else if (typeFullName == "int")
return 0;
return null;
}
#endregion
public static IList<T> SqlDataReaderToIList<T>(SqlDataReader sqldatareader)
{
try
{
IList<T> list = new List<T>();
while (sqldatareader.Read())
{
T t = System.Activator.CreateInstance<T>();
Type type = t.GetType();
for (int i = 0; i < sqldatareader.FieldCount; i++)
{
object TempValue = null;
if (sqldatareader.IsDBNull(i))
{
string typeFullName = type.GetProperty(sqldatareader.GetName(i)).PropertyType.FullName;
TempValue = GetDbNullValue(typeFullName);
}
else
{
TempValue = sqldatareader.GetValue(i);
}
type.GetProperty(sqldatareader.GetName(i)).SetValue(t, TempValue, null);
}
list.Add(t);
}
return list;
}
catch (Exception ex)
{
throw ex;
}
finally
{
sqldatareader.Close();
sqldatareader.Dispose();
}
}
private static object GetDbNullValue(string typeFullName)
{
typeFullName = typeFullName.ToLower();
if (typeFullName == "string")
return string.Empty;
else if (typeFullName == "int32" || typeFullName == "int16" || typeFullName == "int64")
return 0;
else if (typeFullName == "datetime")
return Convert.ToDateTime(DateTime.MinValue);
else if (typeFullName == "boolean")
return false;
else if (typeFullName == "int")
return 0;
return null;
}
#endregion