#region
using System;
using System.Collections;
using System.Data;
using System.Reflection;
#endregion
namespace CSFrameworkV5.Common
{
///
/// DataTable-Object 互转换工具
///
public class DataConverter
{
///
/// 新增一条记录
///
/// 数据表
/// ORM模型
///
public static DataRow AddDataRowFromObject(DataTable dt, object o)
{
var row = dt.NewRow();
var pinfo = o.GetType().GetProperties();
foreach (var info in pinfo)
if (dt.Columns.IndexOf(info.Name) >= 0)
SetDataRowValue(row, info.Name, info.GetValue(o, null));
dt.Rows.Add(row);
return row;
}
///
/// 把一个行的数据新增一个表中
///
///
///
///
public static DataTable AddTableRowByRow(DataTable dt, DataRow dr)
{
var b = false;
var drNew = dt.NewRow();
for (var i = 0; i < dr.Table.Columns.Count; i++)
{
var colname = dr.Table.Columns[i].ColumnName;
if (dt.Columns.IndexOf(colname) >= 0)
{
drNew[colname] = dr[colname];
b = true;
}
}
if (b) dt.Rows.Add(drNew);
return dt;
}
///
/// 根据对象的属性创建数据表
///
private static DataTable BuiltTable(PropertyInfo[] pinfo)
{
try
{
if (pinfo == null) return null;
var table = new DataTable();
foreach (var info in pinfo)
{
var type = info.PropertyType;
if (info.PropertyType.IsGenericType)
type = info.PropertyType.GetGenericArguments()[0];
var column = new DataColumn(info.Name, type);
column.AllowDBNull = true;
table.Columns.Add(column);
}
return table;
}
catch
{
return null;
}
}
///
/// 指定参数是否可用于浅拷贝
///
private static bool CanShallowCopyProperty(object propValue)
{
if (propValue == null) return true;
if (propValue.GetType().IsValueType || propValue is string)
return true;
return false;
}
///
/// 复制对象. 浅拷贝.
///
public static object CloneObject(object source)
{
try
{
if (source == null) return null;
var objType = source.GetType();
var destObj = objType.Assembly.CreateInstance(objType.FullName);
var propsSource = objType.GetProperties();
foreach (var infoSource in propsSource)
{
var value = GetValueOfObject(source, infoSource.Name);
if (value != null && CanShallowCopyProperty(value))
SetPropertyValue(destObj, infoSource, value);
}
return destObj;
}
catch
{
return null;
}
}
///
/// 复制一个对象数组.
///
public static ArrayList CloneObjects(IList source)
{
if (source == null) return null;
var ret = new ArrayList();
foreach (var o in source) ret.Add(CloneObject(o));
return ret;
}
/////
///// SQL SERVER数据类型(如:varchar)转换为DbType类型
/////
///// SQL SERVER数据类型
///// 返回DbType类型
//public static DbType SqlTypeString2SqlType(string sqlTypeString)
//{
// DbType dbType = DbType.Object;//默认为Object
// switch (sqlTypeString)
// {
// case "int":
// dbType = DbType.Int32;
// break;
// case "varchar":
// dbType = DbType.String;
// break;
// case "bit":
// dbType = DbType.Boolean;
// break;
// case "datetime":
// dbType = DbType.DateTime;
// break;
// case "decimal":
// dbType = DbType.Decimal;
// break;
// case "float":
// dbType = DbType.Float;
// break;
// case "image":
// dbType = DbType.Binary;
// break;
// case "money":
// dbType = DbType.Money;
// break;
// case "ntext":
// dbType = DbType.NText;
// break;
// case "nvarchar":
// dbType = DbType.String;
// break;
// case "smalldatetime":
// dbType = DbType.SmallDateTime;
// break;
// case "smallint":
// dbType = DbType.SmallInt;
// break;
// case "text":
// dbType = DbType.Text;
// break;
// case "bigint":
// dbType = DbType.BigInt;
// break;
// case "binary":
// dbType = DbType.Binary;
// break;
// case "char":
// dbType = DbType.String;
// break;
// case "nchar":
// dbType = DbType.NChar;
// break;
// case "numeric":
// dbType = DbType.Decimal;
// break;
// case "real":
// dbType = DbType.Real;
// break;
// case "smallmoney":
// dbType = DbType.SmallMoney;
// break;
// case "sql_variant":
// dbType = DbType.Variant;
// break;
// case "timestamp":
// dbType = DbType.Timestamp;
// break;
// case "tinyint":
// dbType = DbType.TinyInt;
// break;
// case "uniqueidentifier":
// dbType = DbType.UniqueIdentifier;
// break;
// case "varbinary":
// dbType = DbType.VarBinary;
// break;
// case "xml":
// dbType = DbType.Xml;
// break;
// }
// return dbType;
//}
///
/// 数据表是否存在指定的列(Column)
///
/// 数据表
/// 列的名称
///
public static bool ColumnExists(DataTable dt, string columnName)
{
if (dt == null) return false;
foreach (DataColumn col in dt.Columns)
if (col.ColumnName.ToLower() == columnName.ToLower())
return true;
return false;
}
///
/// Object to Object. 将一个对象转换为指定类型的对象.
/// 注意: destination内的Property必需在source内存在.
///
public static object CopyProperties(object source, Type destination)
{
try
{
if (source == null) return null;
var destObj =
destination.Assembly.CreateInstance(destination.FullName);
var propsDest = destObj.GetType().GetProperties();
foreach (var infoDest in propsDest)
{
var value = GetValueOfObject(source, infoDest.Name);
if (value != null && CanShallowCopyProperty(value))
SetPropertyValue(destObj, infoDest, value);
}
return destObj;
}
catch
{
return null;
}
}
///
/// 复制对象属性.
///
public static void CopyProperties(object source, object destObj)
{
try
{
if (source == null || destObj == null) return;
var propsDest = destObj.GetType().GetProperties();
foreach (var infoDest in propsDest)
{
var value = GetValueOfObject(source, infoDest.Name);
if (value != null && CanShallowCopyProperty(value))
SetPropertyValue(destObj, infoDest, value);
}
}
catch
{
}
}
///
/// 根据类型创建表结构
///
///
///
public static DataTable CreateTable(Type t)
{
return BuiltTable(t.GetProperties());
}
///
/// C#.NET数据类型集合
///
///
public static IList CSharpDataTypes()
{
var list = new ArrayList();
list.Add(typeof(DateTime));
list.Add(typeof(byte));
list.Add(typeof(sbyte));
list.Add(typeof(short));
list.Add(typeof(int));
list.Add(typeof(long));
list.Add(typeof(IntPtr));
list.Add(typeof(ushort));
list.Add(typeof(uint));
list.Add(typeof(ulong));
list.Add(typeof(UIntPtr));
list.Add(typeof(float));
list.Add(typeof(double));
list.Add(typeof(decimal));
list.Add(typeof(bool));
list.Add(typeof(char));
list.Add(typeof(string));
return list;
}
///
/// 数据行(DataRow)转换为对象,对象的Type由type参数决定.
///
public static object DataRowToObject(DataRow row, Type type)
{
if (null == row) return null;
try
{
var o = type.Assembly.CreateInstance(type.FullName);
object v;
var pinfo = type.GetProperties();
foreach (var info in pinfo)
{
v = GetFieldValue(row, info.Name);
if (v != null) SetPropertyValue(o, info, v);
}
return o;
}
catch
{
return null;
}
}
///
/// 查找对象包含指定属性.
///
public static bool FindProperty(object obj, string property)
{
try
{
if (obj == null) return false;
var type = obj.GetType();
var pinfo = type.GetProperties();
foreach (var info in pinfo)
if (info.Name.ToUpper() == property.ToUpper())
return true;
return false;
}
catch
{
return false;
}
}
///
/// 根据对象的属性取字段的值
///
private static object GetFieldValue(DataRow row, string propertyName)
{
if (row == null) return null;
if (row.Table.Columns.IndexOf(propertyName) >= 0)
{
var value = row[propertyName];
if (value != null && value is DateTime)
if ((DateTime)value <= DateTime.MinValue.AddDays(1))
value = null;
return value;
}
return null;
}
///
/// 纵对象数据组取出某一个对象. 参数指定关键字段名称(keyPropName)及值(keyValue).
///
public static object GetObjectByKey(IList objects, string keyPropName,
object keyValue)
{
foreach (var o in objects)
{
var value = GetValueOfObject(o, keyPropName);
if (value == null) continue;
if (value.ToStringEx().ToLower() ==
keyValue.ToStringEx().ToLower()) return o;
}
return null;
}
///
/// 纵对象数据组取出某一个对象. 返回对象指定属性名称(returnPropName)的值
///
public static object GetObjectValueByKey(IList objects,
string keyPropName, object keyValue,
string returnPropName)
{
var o = GetObjectByKey(objects, keyPropName, keyValue);
if (o != null) return GetValueOfObject(o, returnPropName);
return null;
}
///
/// 获取对象指定属性的值
///
public static object GetValueOfObject(object obj, string property)
{
try
{
if (obj == null) return null;
var type = obj.GetType();
var pinfo = type.GetProperties();
foreach (var info in pinfo)
if (info.Name.ToUpper() == property.ToUpper())
return info.GetValue(obj, null);
return null;
}
catch
{
return null;
}
}
///
/// 替换记录对应字段的数据。
///
/// 数据源
/// 需要替换的记录
public static void ReplaceDataRowChanges(DataRow sourceRow,
DataRow destRow)
{
string fieldName;
//循环处理当前记录的所有字段
for (var i = 0; i <= sourceRow.Table.Columns.Count - 1; i++)
{
fieldName = sourceRow.Table.Columns[i].ColumnName;
//如果字段名相同,替换对应字段的数据。
if (destRow.Table.Columns.IndexOf(fieldName) >= 0)
destRow[fieldName] = sourceRow[fieldName];
}
}
///
/// 给资料行赋值
///
/// 资料行
/// 字段名
/// 值
public static void SetDataRowValue(DataRow row, string fieldName,
object value)
{
row[fieldName] = value == null ||
ConvertEx.ToString(value) == Globals.DEF_NULL_VALUE
? DBNull.Value
: value;
}
///
/// 给对象的属性赋值
///
/// 对象实例
/// 属性
/// 值
public static void SetPropertyValue(object instance, PropertyInfo prop,
object value)
{
try
{
if (prop == null) return;
if (prop.PropertyType.ToStringEx() == "System.String")
{
}
else if (prop.PropertyType.ToStringEx() == "System.Decimal")
{
value = decimal.Parse(value.ToStringEx());
}
else if (prop.PropertyType.ToStringEx() == "System.Int32")
{
value = int.Parse(value.ToStringEx());
}
else if (prop.PropertyType.ToStringEx() == "System.Single")
{
value = float.Parse(value.ToStringEx());
}
else if (prop.PropertyType.ToStringEx() == "System.DateTime")
{
value = DateTime.Parse(value.ToStringEx());
}
prop.SetValue(instance, value, null);
}
catch
{
}
}
///
/// 从源行中对相同字段名的列付值
///
///
///
public static void SetTwoRowSameColValue(DataRow drSource, DataRow drTo)
{
for (var i = 0; i < drSource.Table.Columns.Count; i++)
{
var fieldname = drSource.Table.Columns[i].ColumnName;
var col = drTo.Table.Columns[fieldname];
if (col != null) drTo[fieldname] = drSource[fieldname];
}
}
///
/// 给记录的字段赋值
///
/// 记录
/// 字段名
/// 值
public static void SetValueofDataRow(DataRow dr, string field,
object value)
{
try
{
if (dr == null) return;
dr[field] = value;
}
catch
{
}
}
///
/// 设置对象某个属性的值
///
public static void SetValueOfObject(object obj, string property,
object value)
{
try
{
if (obj == null) return;
var type = obj.GetType();
var pinfo = type.GetProperties();
foreach (var info in pinfo)
if (info.Name.ToUpper() == property.ToUpper())
{
SetPropertyValue(obj, info, value);
break;
}
}
catch
{
}
}
///
/// 数据库中与C#中的数据类型对照
///
///
///
public static string SqlTypeToCSharpType(string sqlType)
{
var reval = string.Empty;
switch (sqlType.ToLower())
{
case "int":
reval = "Int32";
break;
case "text":
reval = "String";
break;
case "bigint":
reval = "Int64";
break;
case "binary":
reval = "System.Byte[]";
break;
case "bit":
reval = "Boolean";
break;
case "char":
reval = "String";
break;
case "datetime":
reval = "System.DateTime";
break;
case "decimal":
reval = "System.Decimal";
break;
case "float":
reval = "System.Double";
break;
case "image":
reval = "System.Byte[]";
break;
case "money":
reval = "System.Decimal";
break;
case "nchar":
reval = "String";
break;
case "ntext":
reval = "String";
break;
case "numeric":
reval = "System.Decimal";
break;
case "nvarchar":
reval = "String";
break;
case "real":
reval = "System.Single";
break;
case "smalldatetime":
reval = "System.DateTime";
break;
case "smallint":
reval = "Int16";
break;
case "smallmoney":
reval = "System.Decimal";
break;
case "timestamp":
reval = "System.DateTime";
break;
case "tinyint":
reval = "System.Byte";
break;
case "uniqueidentifier":
reval = "System.Guid";
break;
case "varbinary":
reval = "System.Byte[]";
break;
case "varchar":
reval = "String";
break;
case "Variant":
reval = "Object";
break;
default:
reval = "String";
break;
}
return reval;
}
///
/// DataTable转换为DataSet
///
/// DataTable
///
public static DataSet TableToDataSet(DataTable table)
{
if (table.DataSet != null) return table.DataSet;
var ds = new DataSet();
ds.Tables.Add(table);
return ds;
}
///
/// 对象数组转换为ArrayList.
///
public static ArrayList ToArrayList(IList list)
{
if (list == null) return null;
var arrlist = new ArrayList();
foreach (var o in list) arrlist.Add(o);
return arrlist;
}
///
/// 对象数组转换为ArrayList.
///
public static ArrayList ToArrayList(object[] source)
{
if (null != source) return new ArrayList(source);
//如果来源数据为null,返回一个空的ArrayList.
return new ArrayList();
}
///
/// ArrayList转换为对象数组.
///
public static object[] ToObjects(IList source)
{
if (null == source) return null;
var ret = new object[source.Count];
for (var i = 0; i < source.Count; i++) ret[i] = source[i];
return ret;
}
///
/// 把字符串以逗号分格,转换成数据库格式in('a','b')
///
///
///
public static string ToSQLInDataFormat(string input)
{
var HQL = string.Empty;
if (input == string.Empty) return HQL;
var sArray = input.Split(',');
foreach (var str in sArray)
{
if (str.Length == 0) continue;
HQL += "'" + str + "',";
}
if (HQL.Substring(HQL.Length - 1, 1) == ",")
HQL = HQL.Substring(0, HQL.Length - 1);
return HQL;
}
///
/// 把字符串以逗号分格,转换成数据库格式''a'',''b''
///
public static string ToSQLInDataFormatTwo(string input)
{
var HQL = string.Empty;
if (input == string.Empty) return HQL;
var sArray = input.Split(',');
foreach (var str in sArray)
{
if (str.Length == 0) continue;
HQL += "''" + str + "'',";
}
if (HQL.Substring(HQL.Length - 1, 1) == ",")
HQL = HQL.Substring(0, HQL.Length - 1);
return HQL;
}
///
/// 以逗号分格字符串,返回数组
/// 如果第一个和最后一个字符为, 去掉
///
///
///
public static string[] ToStringSplit(string str)
{
if (str.Length > 0)
{
if (str[0] == ',') str = str.Substring(1, str.Length - 1);
if (str[str.Length - 1] == ',')
str = str.Substring(0, str.Length - 1);
}
var sArray = str.Split(',');
return sArray;
}
///
/// 由某对象更新资料行,字段名称必须与对象属性对应,(ORM模型)
///
/// 资料行
/// 对象实例
///
public static DataRow UpdateDataRowFromObject(DataRow row, object o)
{
var pinfo = o.GetType().GetProperties();
foreach (var info in pinfo)
if (row.Table.Columns.IndexOf(info.Name) >= 0)
SetDataRowValue(row, info.Name, info.GetValue(o, null));
return row;
}
///
/// 修改对表的某列的值
///
///
///
public static bool UpdateTableCol(DataTable dt, string fieldName,
object value)
{
try
{
if (dt.Columns.IndexOf(fieldName) < 0)
throw new Exception("表没有" + fieldName + "列!");
foreach (DataRow dr in dt.Rows) dr[fieldName] = value;
return true;
}
catch
{
return false;
}
}
}
}