Table转换成实体、Table转换成实体集合(可转换成对象和值类型)

/// Table转换成实体
public static T ToEntity<T>(this DataTable table) where T : class, new()
{
  if (table == null || table.Rows == null || table.Rows.Count <= 0)
  {
    return default(T);
  }
  var entity = (T)Activator.CreateInstance(typeof(T));
  var row = table.Rows[0];
  var properties = typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public);

  foreach (var property in properties)
  {
    if (table.Columns.Contains(property.Name))
    {
      if (!IsNullOrDBNull(row[property.Name]))
      {
        property.SetValue(entity, HackType(row[property.Name], property.PropertyType), null);
      }
    }
  }
  return entity;
}


/// Table转换成实体集合(可转换成对象和值类型)
public static List<T> ToList<T>(this DataTable table)
{
  var list = new List<T>();
  var properties = typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public);
  for (var i = 0; i < table.Rows.Count; i++)
  {
    var row = table.Rows[i];
    T entity;
    var tType = typeof(T);
    if (!(tType == typeof(string)) && (tType.IsClass || tType.IsGenericType))
    {
      entity = (T)Activator.CreateInstance(typeof(T));
      foreach (var property in properties)
      {
        if (table.Columns.Contains(property.Name))
        {
          if (!IsNullOrDBNull(row[property.Name]))
          {
            property.SetValue(entity, HackType(row[property.Name], property.PropertyType), null);
          }
        }
      }
    }
    else
    {
      //entity = default(T);
      entity = ConvertUtils.To(row[0], default(T));
    }
    list.Add(entity);
  }
  return list;
}

posted @ 2018-07-06 15:56  GU天乐乐乐!  阅读(310)  评论(1编辑  收藏  举报