Hi all,
I am trying to use some code found on cp. The one with the tick
This db mapper works but not with nullable types. The method below just loops through datatablerow and fills a class
i am trying to call with this method but how do I pass the T when I call ?
I want to convert the above method so it will use method below to call setvalue method?
Age is a consequence of experience
I am trying to use some code found on cp. The one with the tick
This db mapper works but not with nullable types. The method below just loops through datatablerow and fills a class
i am trying to call with this method but how do I pass the T when I call ?
Code:
public static T DataTableToObject<T>( DataTable dt, int row) where T : new()
{
//string temp = "assignment";
//string temp1 = temp.Replace("a", "A");
//List<string> propNames = new List<string>();
PropertyInfo[] pi = typeof(T).GetProperties();
T objectName = new T();
int index = -1;
for (int i = 0; i < dt.Columns.Count; i++)
{
string colName = dt.Columns[i].ColumnName;
index = GetNamedPropertyIndex(colName, pi);
if (index != -1)
{
// this is a reference to the class property
// so what we do to this will be done to the class
PropertyInfo classProperty = pi[index];
if (colName.Equals(classProperty.Name, StringComparison.InvariantCultureIgnoreCase))
{
object cellValue = dt.Rows[row][colName];
Type cellType = dt.Rows[row][colName].GetType();
try
{
if (cellValue != DBNull.Value)
{
if (cellValue == DBNull.Value && classProperty.PropertyType.Name == "Int32")
cellValue = -1;
else if (cellValue == DBNull.Value && classProperty.PropertyType.Name == "Boolean")
cellValue = false;
if (cellValue == DBNull.Value && classProperty.PropertyType.Name == "DateTime")
cellValue = System.DateTime.MinValue;
if (cellType.ToString() == "System.Guid")
cellValue = cellValue.ToString();
else if (cellType.ToString() == "System.String")
cellValue = @cellValue.ToString();
else
cellValue = Convert.ChangeType(cellValue, classProperty.PropertyType);
classProperty.SetValue(objectName, cellValue, null);
}
}
catch (Exception ex)
{
throw new Exception("Error in Mapper converting the DT row to an object " +
objectName.ToString() + "on property " + classProperty.Name, ex);
}
}
}
}
return objectName;
I want to convert the above method so it will use method below to call setvalue method?
Code:
public static T1 To<T1>(object obj)
where T1 : class
{
Type t = typeof(T1);
Type u = Nullable.GetUnderlyingType(t);
if (u != null)
{
if (obj == null)
return default(T1);
return (T1)Convert.ChangeType(obj, u);
}
else
{
return (T1)Convert.ChangeType(obj, t);
}
}
Age is a consequence of experience