123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Reflection;
- using System.Data;
- using Ant.Frame;
- using System.Data.SqlClient;
- using System.Linq.Expressions;
- using System.ComponentModel;
- using System.Collections;
- namespace Ant.ORM
- {
- public static class DataToModel
- {
- #region 将DataTable转换成List列表
- #region 返回一条实体数据
- /// <summary>
- /// DataReader转实体
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="rdr"></param>
- /// <returns></returns>
- public static T Dr2En<T>(IDataReader rdr) where T : class
- {
- DataTable dtt = Dr2Dt(rdr);
- return Dt2En<T>(dtt); ;
- }
- public static T Dr2En<T>(IDataReader rdr, object enty) where T : class
- {
- DataTable dtt = Dr2Dt(rdr);
- return Dt2En<T>(dtt, enty); ;
- }
- /// <summary>
- /// DataReader转Object
- /// </summary>
- /// <param name="rdr"></param>
- /// <param name="entity"></param>
- /// <returns></returns>
- public static T Dr2EnObj<T>(IDataReader rdr, T entity) where T : class
- {
- DataTable dtt = Dr2Dt(rdr);
- return Dt2EnObj<T>(dtt, entity);
- }
- /// <summary>
- /// 返回一条实体数据
- /// </summary>
- /// <typeparam name="T">实体</typeparam>
- /// <param name="dataTable">表数据</param>
- /// <returns></returns>
- public static T Dt2En<T>(DataTable dataTable) where T : class
- {
- T obj = default(T);
- if (dataTable.Rows.Count > 0)
- {
- var md = MetaDataManager.GetMetaData(typeof(T));
- obj = Activator.CreateInstance<T>();
- DataRow row = dataTable.Rows[0];
- obj = DtSetValueFieldOld(row, obj, md) as T;
- }
- return obj;
- }
- /// <summary>
- /// 返回一条实体数据
- /// </summary>
- /// <typeparam name="T">实体</typeparam>
- /// <param name="dataTable">表数据</param>
- /// <returns></returns>
- public static T Dt2En<T>(DataTable dataTable, object enty) where T : class
- {
- var md = MetaDataManager.GetMetaData(enty.GetType());
- T obj = Activator.CreateInstance<T>();
- obj = enty as T;
- if (dataTable.Rows.Count > 0)
- {
- DataRow row = dataTable.Rows[0];
- obj = DtSetValueFieldOld(row, obj, md) as T;
- }
- return obj;
- }
- /// <summary>
- /// 返回一条实体数据
- /// </summary>
- /// <typeparam name="T">实体</typeparam>
- /// <param name="dataTable">表数据</param>
- /// <returns></returns>
- public static object Dt2EnObj<T>(DataTable dt) where T : class
- {
- var md = MetaDataManager.GetMetaData(typeof(T));
- T obj = Activator.CreateInstance<T>();
- if (dt.Rows.Count > 0)
- {
- DataRow row = dt.Rows[0];
- obj = DtSetValueFieldOld(row, obj, md) as T;
- }
- return obj;
- }
- /// <summary>
- /// 获取一条实体
- /// </summary>
- /// <param name="dt"></param>
- /// <param name="enty"></param>
- /// <returns></returns>
- public static T Dt2EnObj<T>(DataTable dt, T enty) where T : class
- {
- var md = MetaDataManager.GetMetaData(enty.GetType());
- T obj = Activator.CreateInstance(md.EntityType) as T;
- if (dt == null) return obj;
- if (dt.Rows.Count == 0) return obj;
- DataRow dr = dt.Rows[0];
- obj = (T)DtSetValueFieldOld(dr, obj, md);
- return obj;
- }
- #endregion
- #region 返回实体集合
- /// <summary>
- /// DataReader转object
- /// </summary>
- /// <param name="rdr"></param>
- /// <param name="entity"></param>
- /// <returns></returns>
- public static List<T> Dr2EnList<T>(IDataReader rdr, T entity) where T : class
- {
- DataTable dtt = Dr2Dt(rdr);
- return Dt2EnList<T>(dtt, entity);
- }
- /// <summary>
- /// DataReader转实体集合
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="rdr"></param>
- /// <returns></returns>
- public static List<T> Dr2EnList<T>(IDataReader rdr)
- {
- DataTable dtt = Dr2Dt(rdr);
- List<T> listobj = Dt2EnList<T>(dtt);
- return listobj;
- }
- /// <summary>
- /// 将DataTable转换为list(用的FOR赋值,效果一样,这种比较复杂)
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="dt"></param>
- /// <returns></returns>
- public static List<T> Dt2EnList<T>(DataTable dt)
- {
- List<T> list = new List<T>();
- var md = MetaDataManager.GetMetaData(typeof(T));
- if (dt == null) return list;
- foreach (DataRow row in dt.Rows)
- {
- T obj = Activator.CreateInstance<T>();
- obj = (T)DtSetValueField(row, obj, md);
- list.Add(obj);
- }
- return list;
- }
- /// <summary>
- /// 将DataTable转换为list(用的FOR赋值,效果一样,这种比较复杂)
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="dt"></param>
- /// <returns></returns>
- public static List<T> Dt2EnList<T>(T obj, DataTable dt) where T : class
- {
- List<T> list = new List<T>();
- if (dt == null) return list;
- var md = MetaDataManager.GetMetaData(typeof(T));
- foreach (DataRow row in dt.Rows)
- {
- T objj = obj;
- objj = DtSetValueField(row, objj, md) as T;
- list.Add(objj);
- }
- return list;
- }
- /// <summary>
- /// DataTable转换成实体列表此方法是实体属性不带?的可以这样转换
- /// </summary>
- /// <typeparam name="T">实体 T </typeparam>
- /// <param name="table">datatable</param>
- /// <returns></returns>
- public static IList<T> DtToList<T>(DataTable table)
- where T : class
- {
- IList<T> list = new List<T>();
- if (!table.IsHaveRows()) return list;
- T model = default(T);
- foreach (DataRow dr in table.Rows)
- {
- model = Activator.CreateInstance<T>();
- foreach (DataColumn dc in dr.Table.Columns)
- {
- object drValue = dr[dc.ColumnName];
- PropertyInfo pi = model.GetType().GetProperty(dc.ColumnName,
- BindingFlags.Public | BindingFlags.NonPublic
- | BindingFlags.Instance | BindingFlags.IgnoreCase);
- if (pi != null && pi.CanWrite && (drValue != null && !Convert.IsDBNull(drValue)))
- {
- pi.SetValue(model, drValue, null);
- }
- }
- list.Add(model);
- }
- return list;
- }
- /// <summary>
- /// 将表数据转换成实体集合
- /// </summary>
- /// <param name="dataTable">表数据</param>
- /// <param name="enty">实体</param>
- /// <returns></returns>
- public static List<T> Dt2EnList<T>(DataTable dt, T enty) where T : class
- {
- List<T> list = new List<T>();
- if (!dt.IsHaveRows()) return list;
- var md = MetaDataManager.GetMetaData(typeof(T));
- foreach (DataRow row in dt.Rows)
- {
- T obj = Activator.CreateInstance(enty.GetType()) as T;
- obj = (T)DtSetValueFieldOld(row, obj, md);
- list.Add(obj);
- }
- return list;
- }
- #endregion
- #region 公共调用用DataRow给实体进行赋值
- public static List<T> ReaderToList<T>(IDataReader dr)
- {
- using (dr)
- {
- var md = MetaDataManager.GetMetaData(typeof(T));
- List<string> list = new List<string>(dr.FieldCount);
- for (int i = 0; i < dr.FieldCount; i++)
- {
- list.Add(dr.GetName(i).ToLower());
- }
- List<T> list2 = new List<T>();
- while (dr.Read())
- {
- T local = Activator.CreateInstance<T>();
- foreach (PropertyInfo info in md.Propertys)
- {
- if (list.Contains(info.Name.ToLower()) && !IsNullOrDBNull(dr[info.Name]))
- {
- info.SetValue(local, HackType(dr[info.Name], info.PropertyType), null);
- }
- }
- list2.Add(local);
- }
- return list2;
- }
- }
- /// <summary>
- /// 给实体进行赋值
- /// </summary>
- /// <param name="row"></param>
- /// <param name="objj"></param>
- /// <returns></returns>
- private static object DtSetValueFieldOld(DataRow row, object objj, FiledMetaData md)
- {
- // Dictionary<string, EntityValue> vl = new Dictionary<string, EntityValue>();
- foreach (DataColumn dc in row.Table.Columns)
- {
- PropertyInfo pinfo = md.EntityType.GetProperty(dc.ColumnName.ToLower(),
- BindingFlags.Public | BindingFlags.NonPublic
- | BindingFlags.Instance | BindingFlags.IgnoreCase);//这种如何实现有待解决,现在解决方法就是将实体属性的标签的名称和实体名称大写完全一样,这样才能保证这边不报错
- try
- {
- if (String.Compare(dc.ColumnName, "Version", true) == 0)
- {
- byte[] bts = (byte[])(row[dc.ColumnName]);
- Array.Reverse(bts);
- long num = BitConverter.ToInt64(bts, 0);
- pinfo.SetValue(objj, num, null);
- }
- else
- {
- object drValue = row[dc.ColumnName];
- if (pinfo != null && pinfo.CanWrite && (drValue != null && !Convert.IsDBNull(drValue)))
- {
- if (pinfo.PropertyType == typeof(Int64) || pinfo.PropertyType == typeof(Int64?))
- //if (pinfo.PropertyType.ToString().ToLower().Contains("system.int64"))
- pinfo.SetValue(objj, Convert.ToInt32(drValue), null);
- else if (pinfo.PropertyType == typeof(Int32) || pinfo.PropertyType == typeof(Int32?))
- pinfo.SetValue(objj, Convert.ToInt32(drValue), null);
- else if (pinfo.PropertyType == typeof(DateTime) || pinfo.PropertyType == typeof(DateTime?))
- pinfo.SetValue(objj, Convert.ToDateTime(drValue), null);
- else if (pinfo.PropertyType == typeof(Boolean) || pinfo.PropertyType == typeof(Boolean?))
- pinfo.SetValue(objj, Convert.ToBoolean(drValue), null);
- else if (pinfo.PropertyType == typeof(Single) || pinfo.PropertyType == typeof(Single?))
- pinfo.SetValue(objj, Convert.ToSingle(drValue), null);
- else if (pinfo.PropertyType == typeof(Double) || pinfo.PropertyType == typeof(Double?))
- pinfo.SetValue(objj, Convert.ToDouble(drValue), null);
- else if (pinfo.PropertyType == typeof(Decimal) || pinfo.PropertyType == typeof(Decimal?))
- pinfo.SetValue(objj, Convert.ToDecimal(drValue), null);
- else if (pinfo.PropertyType == typeof(Guid) || pinfo.PropertyType == typeof(Guid?))
- pinfo.SetValue(objj, new Guid(drValue.ToString()), null);
- else if (pinfo.PropertyType == typeof(Byte) || pinfo.PropertyType == typeof(Byte?))
- pinfo.SetValue(objj, Convert.ToByte(drValue), null);
- else if (pinfo.PropertyType == typeof(SByte) || pinfo.PropertyType == typeof(SByte?))
- pinfo.SetValue(objj, Convert.ToSByte(drValue), null);
- else if (pinfo.PropertyType == typeof(Int16) || pinfo.PropertyType == typeof(Int16?))
- pinfo.SetValue(objj, Convert.ToInt16(drValue), null);
- else if (pinfo.PropertyType == typeof(Char) || pinfo.PropertyType == typeof(Char?))
- pinfo.SetValue(objj, Convert.ToChar(drValue), null);
- else
- pinfo.SetValue(objj, drValue, null);
- #region 旧版本
- #region Compare是比较相等
- //if (string.Compare(pinfo.PropertyType.ToString(), "system.int32", true) == 0)
- // pinfo.SetValue(objj, Convert.ToInt32(drValue), null);
- //else if (string.Compare(pinfo.PropertyType.ToString(), "system.int64", true) == 0)
- // pinfo.SetValue(objj, Convert.ToInt64(drValue), null);
- //else if (string.Compare(pinfo.PropertyType.ToString(), "system.boolean", true) == 0)
- // pinfo.SetValue(objj, Convert.ToBoolean(drValue), null);
- //else if (string.Compare(pinfo.PropertyType.ToString(), "system.datetime", true) == 0)
- // pinfo.SetValue(objj, Convert.ToDateTime(drValue), null);
- //else if (string.Compare(pinfo.PropertyType.ToString(), "system.decimal", true) == 0)
- // pinfo.SetValue(objj, Convert.ToDecimal(drValue), null);
- //else if (string.Compare(pinfo.PropertyType.ToString(), "system.double", true) == 0)
- // pinfo.SetValue(objj, Convert.ToDouble(drValue), null);
- //else
- // pinfo.SetValue(objj, drValue, null);
- #endregion
- #region 不用了
- //switch (pinfo.PropertyType.ToString().ToLower())
- //{
- // case "system.int32":
- // pinfo.SetValue(objj, Convert.ToInt32(drValue), null);
- // break;
- // case "system.boolean":
- // pinfo.SetValue(objj, Convert.ToBoolean(drValue), null);
- // break;
- // case "system.datetime":
- // pinfo.SetValue(objj, Convert.ToDateTime(drValue), null);
- // break;
- // case "system.decimal":
- // pinfo.SetValue(objj, Convert.ToDecimal(drValue), null);
- // break;
- // case "system.double":
- // pinfo.SetValue(objj, Convert.ToDouble(drValue), null);
- // break;
- // default:
- // pinfo.SetValue(objj, drValue, null);
- // break;
- //}
- #endregion
- #region 另一种实现
- //另一种在一定条件可以实现的方法
- //pinfo.SetValue(objj, Convert.ChangeType(drValue, pinfo.PropertyType), null);
- //如果实体中带?的时就不能用这种方式,实体中带?是代表可空,实体作为查询条件的时候必须把值类型加?
- //这样实例的时候就默认为Null,实体中带?就用上面那种强制转换;
- #endregion
- #endregion
- }
- else
- {
- if (pinfo != null && pinfo.CanWrite)
- pinfo.SetValue(objj, null, null);
- }
- }
- }
- catch (Exception ex)
- {
- pinfo.SetValue(objj, null, null);
- }
- }
- PropertyInfo pi = md.EntityType.GetProperty("PersistType",
- BindingFlags.Public | BindingFlags.NonPublic
- | BindingFlags.Instance | BindingFlags.IgnoreCase);
- if (pi != null && pi.CanWrite)
- pi.SetValue(objj, EntityPersistType.Update, null);
- return objj;
- }
- /// <summary>
- /// 给实体进行赋值
- /// </summary>
- /// <param name="row"></param>
- /// <param name="objj"></param>
- /// <returns></returns>
- private static T DtSetValueField<T>(DataRow row, T objj, FiledMetaData md)
- {
- // Dictionary<string, EntityValue> vl = new Dictionary<string, EntityValue>();
- foreach (DataColumn dc in row.Table.Columns)
- {
- PropertyInfo pinfo = md.EntityType.GetProperty(dc.ColumnName.ToLower(),
- BindingFlags.Public | BindingFlags.NonPublic
- | BindingFlags.Instance | BindingFlags.IgnoreCase);//这种如何实现有待解决,现在解决方法就是将实体属性的标签的名称和实体名称大写完全一样,这样才能保证这边不报错
- //PropertyInfo pinfo = objj.GetType().GetProperty(dc.ColumnName.ToLower(),
- // BindingFlags.Public | BindingFlags.NonPublic
- // | BindingFlags.Instance | BindingFlags.IgnoreCase);//这种如何实现有待解决,现在解决方法就是将实体属性的标签的名称和实体名称大写完全一样,这样才能保证这边不报错
- try
- {
- if (String.Compare(dc.ColumnName, "Version", true) == 0)//给时间戳赋值
- {
- byte[] bts = (byte[])(row[dc.ColumnName]);
- Array.Reverse(bts);
- long num = BitConverter.ToInt64(bts, 0);
- pinfo.SetValue(objj, num, null);
- }
- else
- {
- object drValue = row[dc.ColumnName];
- if (pinfo != null && pinfo.CanWrite && (drValue != null && !Convert.IsDBNull(drValue)))
- {
- if (!pinfo.PropertyType.IsGenericType)
- {
- //非泛型
- pinfo.SetValue(objj, Convert.ChangeType(drValue, pinfo.PropertyType), null);
- }
- else
- {
- //泛型Nullable<>
- Type genericTypeDefinition = pinfo.PropertyType.GetGenericTypeDefinition();
- if (genericTypeDefinition == typeof(Nullable<>))
- {
- pinfo.SetValue(objj, Convert.ChangeType(drValue, Nullable.GetUnderlyingType(pinfo.PropertyType)), null);
- }
- }
- }
- else
- {
- if (pinfo != null && pinfo.CanWrite)
- pinfo.SetValue(objj, null, null);
- }
- }
- }
- catch (Exception ex)
- {
- pinfo.SetValue(objj, null, null);
- }
- }
- PropertyInfo pi = md.EntityType.GetProperty("PersistType",
- BindingFlags.Public | BindingFlags.NonPublic
- | BindingFlags.Instance | BindingFlags.IgnoreCase);
- if (pi != null && pi.CanWrite)
- pi.SetValue(objj, EntityPersistType.Update, null);
- return objj;
- }
- /// <summary>
- /// 给牧举赋值
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="value"></param>
- /// <param name="ordinal"></param>
- /// <returns></returns>
- public static T GetEnum<T>(object value) where T : struct
- {
- T t = (T)Enum.ToObject(typeof(T), value);
- return t;
- }
- /// <summary>
- /// 可空牧举赋值
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="value"></param>
- /// <param name="ordinal"></param>
- /// <returns></returns>
- public static T? GetEnum_Nullable<T>(object value, int ordinal) where T : struct
- {
- if (value.IsNull())
- {
- return null;
- }
- else
- {
- T t = (T)Enum.ToObject(typeof(T), value);
- return t;
- }
- }
- /// <summary>
- /// 调用说明:
- /// int intValue1 = "123".ConvertTo<int>();
- /// int? intValue2 = "123".ConvertTo<int?>();
- /// DateTime dateTimeValue1 = "1981-08-24".ConvertTo<DateTime>();
- /// DateTime? dateTimeValue2 = "1981-08-24".ConvertTo<DateTime?>();
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="convertibleValue"></param>
- /// <returns></returns>
- public static T ConvertTo<T>(this IConvertible convertibleValue)
- {
- if (null == convertibleValue)
- {
- return default(T);
- }
- if (!typeof(T).IsGenericType)
- {
- return (T)Convert.ChangeType(convertibleValue, typeof(T));
- }
- else
- {
- Type genericTypeDefinition = typeof(T).GetGenericTypeDefinition();
- if (genericTypeDefinition == typeof(Nullable<>))
- {
- return (T)Convert.ChangeType(convertibleValue, Nullable.GetUnderlyingType(typeof(T)));
- }
- }
- throw new InvalidCastException(string.Format("Invalid cast from type \"{0}\" to type \"{1}\".", convertibleValue.GetType().FullName, typeof(T).FullName));
- }
- /// <summary>
- /// 检查DataTable 是否有数据行
- /// </summary>
- /// <param name="dt">DataTable</param>
- /// <returns></returns>
- public static bool IsHaveRows(this DataTable dt)
- {
- if (dt != null && dt.Rows.Count > 0)
- return true;
- return false;
- }
- /// <summary>
- /// DataReader转DataTable
- /// </summary>
- /// <param name="rdr"></param>
- /// <returns></returns>
- public static DataTable Dr2Dt(IDataReader rdr)
- {
- DataTable dtReturn = new DataTable();
- DataColumn dc = null;
- DataRow dr = null;
- for (int i = 0; i < rdr.GetSchemaTable().Rows.Count; i++)
- {
- dr = rdr.GetSchemaTable().Rows[i];
- dc = new DataColumn(dr["ColumnName"].ToString(), dr["DataType"] as Type);
- if (!dtReturn.Columns.Contains(dr["ColumnName"].ToString()))
- {
- dtReturn.Columns.Add(dc);
- }
- }
- object[] value = new object[dtReturn.Columns.Count];
- while (rdr.Read())
- {
- rdr.GetValues(value);
- dtReturn.LoadDataRow(value, true);
- }
- return dtReturn;
- }
- /// <summary>
- ///
- /// </summary>
- /// <param name="dataReader"></param>
- /// <returns></returns>
- public static DataTable ConvertDataReaderToDataTable(IDataReader dataReader)
- {
- ///定义DataTable
- DataTable datatable = new DataTable();
- try
- { ///动态添加表的数据列
- for (int i = 0; i < dataReader.FieldCount; i++)
- {
- DataColumn myDataColumn = new DataColumn();
- myDataColumn.DataType = dataReader.GetFieldType(i);
- myDataColumn.ColumnName = dataReader.GetName(i);
- datatable.Columns.Add(myDataColumn);
- }
- ///添加表的数据
- while (dataReader.Read())
- {
- DataRow myDataRow = datatable.NewRow();
- for (int i = 0; i < dataReader.FieldCount; i++)
- {
- myDataRow[i] = dataReader[i].ToString();
- }
- datatable.Rows.Add(myDataRow);
- myDataRow = null;
- }
- ///关闭数据读取器
- dataReader.Close();
- return datatable;
- }
- catch (Exception ex)
- {
- ///抛出类型转换错误
- //SystemError.CreateErrorLog(ex.Message);
- throw new Exception(ex.Message, ex);
- }
- }
- /// <summary>
- /// DataReader转DataTable
- /// </summary>
- /// <param name="reader"></param>
- /// <returns></returns>
- public static DataTable ReaderToDataTable(IDataReader reader)
- {
- DataTable table = new DataTable("Table");
- int fieldCount = reader.FieldCount;
- for (int i = 0; i < fieldCount; i++)
- {
- table.Columns.Add(reader.GetName(i).ToLower(), reader.GetFieldType(i));
- }
- table.BeginLoadData();
- object[] values = new object[fieldCount];
- while (reader.Read())
- {
- reader.GetValues(values);
- table.LoadDataRow(values, true);
- }
- reader.Close();
- table.EndLoadData();
- return table;
- }
- #endregion
- #endregion
- #region 备份
- ///// <summary>
- ///// 给实体进行赋值
- ///// </summary>
- ///// <param name="row"></param>
- ///// <param name="objj"></param>
- ///// <returns></returns>
- //private static object DtSetValueField(DataRow row, object objj)
- //{
- // Dictionary<string, EntityValue> vl = new Dictionary<string, EntityValue>();
- // foreach (PropertyInfo pinfo in objj.GetType().GetProperties())
- // {
- // DataFieldColumnAttribute dfa = Attribute.GetCustomAttribute(pinfo, typeof(DataFieldColumnAttribute)) as DataFieldColumnAttribute;
- // if (!object.Equals(dfa, null))
- // {
- // try
- // {
- // //if (!Convert.IsDBNull(row[pinfo.Name]))
- // object drValue = row[pinfo.Name];
- // if (pinfo != null && pinfo.CanWrite && (drValue != null && !Convert.IsDBNull(drValue)))
- // {
- // vl = SetChanaged(pinfo.Name, row[pinfo.Name], vl);
- // #region 备份暂时不用
- // //if (pinfo.PropertyType.ToString().ToLower().Contains("system.int64"))
- // // pinfo.SetValue(objj, Convert.ToInt64(row[pinfo.Name]), null);
- // //else if (pinfo.PropertyType.ToString().ToLower().Contains("system.int32"))
- // // pinfo.SetValue(objj, Convert.ToInt32(row[pinfo.Name]), null);
- // //else
- // // pinfo.SetValue(objj, row[pinfo.Name], null);
- // #endregion
- // pinfo.SetValue(objj, Convert.ChangeType(row[pinfo.Name], pinfo.PropertyType.GetType()), null);
- // }
- // else
- // pinfo.SetValue(objj, null, null);
- // }
- // catch (Exception ex)
- // {
- // pinfo.SetValue(objj, null, null);
- //
- // }
- // }
- // if (pinfo.Name.Contains("PersistType"))
- // pinfo.SetValue(objj, EntityPersistType.Update, null);
- // if (pinfo.Name.Contains("Values"))
- // pinfo.SetValue(objj, vl, null);
- // }
- // return objj;
- //}
- ///// <summary>
- ///// 将DataTable转换为list(用的FOR赋值,效果一样,这种比较复杂)
- ///// </summary>
- ///// <typeparam name="T"></typeparam>
- ///// <param name="dt"></param>
- ///// <returns></returns>
- //public static T DataReader2Mod<T>(IDataReader dr)
- //{
- // T objj = (T)Activator.CreateInstance(typeof(T));
- // if (dr == null) return objj;
- // PropertyInfo[] propertys = objj.GetType().GetProperties();
- // foreach (PropertyInfo pi in propertys)
- // {
- // //DataTable MyDataTable = dr.GetSchemaTable();
- // //foreach (DataRow row in MyDataTable.Rows)
- // //{
- // // foreach (DataColumn col in MyDataTable.Columns)
- // // {
- // #region 属性与字段名称一致的进行赋值
- // // if (pi.Name.ToLower().Equals(row[0].ToString().ToLower()))
- // // {
- // // try
- // // {
- // // if (!Convert.IsDBNull(dr[row[0].ToString()]))
- // // {
- // // if (pi.PropertyType.ToString().ToLower().Contains("system.int64"))
- // // {
- // // pi.SetValue(obj, Convert.ToInt64(dr[pi.Name]), null);
- // // }
- // // if (pi.PropertyType.ToString().ToLower().Contains("system.int32"))
- // // {
- // // pi.SetValue(obj, dr[pi.Name].ToInt32(), null);
- // // }
- // // else
- // // {
- // // pi.SetValue(obj, row[pi.Name], null);
- // // }
- // // }
- // // else
- // // pi.SetValue(obj, null, null);//为空,但不为Null
- // // }
- // // catch (Exception ex)
- // // {
- // // pi.SetValue(obj, null, null);//为空,但不为Null
- // //
- // // }
- // // }
- // #endregion
- // // }
- // //}
- // for (int k = 0; k < dr.FieldCount; k++)
- // {
- // if (!DBNull.Value.Equals(dr.GetValue(k)))
- // {
- // if (pi.PropertyType.ToString().ToLower().Contains("system.int64"))
- // pi.SetValue(objj, Convert.ToInt64(dr.GetValue(k)), null);
- // else if (pi.PropertyType.ToString().ToLower().Contains("system.int32"))
- // pi.SetValue(objj, dr.GetValue(k).ToInt32(), null);
- // else
- // pi.SetValue(objj, dr.GetValue(k), null);
- // }
- // }
- // if (pi.Name.Contains("PersistType"))
- // {
- // pi.SetValue(objj, EntityPersistType.Update, null);
- // }
- // }
- // return objj;
- //}
- ///// <summary>
- ///// 这样也可以不过entity每次的值还在,缺点就是无法清除原先的值
- ///// </summary>
- ///// <param name="dr"></param>
- ///// <param name="md"></param>
- ///// <param name="enty"></param>
- ///// <returns></returns>
- //public static object DataReader2Entity(IDataReader dr, object enty)
- //{
- // object objj = Activator.CreateInstance(enty.GetType());
- // if (dr == null) return objj;
- // PropertyInfo[] propertys = enty.GetType().GetProperties();
- // foreach (PropertyInfo pi in propertys)
- // {
- // DataTable MyDataTable = dr.GetSchemaTable();
- // foreach (DataRow row in MyDataTable.Rows)
- // {
- // foreach (DataColumn col in MyDataTable.Columns)
- // {
- // #region 属性与字段名称一致的进行赋值
- // if (pi.Name.ToLower().Equals(row[0].ToString().ToLower()))
- // {
- // try
- // {
- // if (!Convert.IsDBNull(dr[row[0].ToString()]))
- // {
- // if (pi.PropertyType.ToString().ToLower().Contains("system.int64"))
- // pi.SetValue(objj, Convert.ToInt64(dr[pi.Name]), null);
- // else if (pi.PropertyType.ToString().ToLower().Contains("system.int32"))
- // pi.SetValue(objj, dr[pi.Name].ToInt32(), null);
- // else
- // pi.SetValue(objj, row[pi.Name], null);
- // }
- // else
- // pi.SetValue(objj, null, null);//为空,但不为Null
- // }
- // catch (Exception ex)
- // {
- // pi.SetValue(objj, null, null);//为空,但不为Null
- //
- // }
- // }
- // #endregion
- // }
- // if (pi.Name.Contains("PersistType"))
- // {
- // pi.SetValue(objj, EntityPersistType.Update, null);
- // }
- // }
- // }
- // return objj;
- //}
- ///// <summary>
- ///// 将DataTable转换为list(用的FOR赋值,效果一样,这种比较复杂)
- ///// </summary>
- ///// <typeparam name="T"></typeparam>
- ///// <param name="dt"></param>
- ///// <returns></returns>
- //public static List<T> DataTable2List<T>(DataTable dt)
- //{
- // List<T> result = new List<T>(); string colname = "";
- // MetaData md = MetaDataManager.GetMetaData(typeof(T));
- // if (dt == null) return result;
- // for (int j = 0; j < dt.Rows.Count; j++)
- // {
- // T objj = (T)Activator.CreateInstance(typeof(T));
- // PropertyInfo[] propertys = objj.GetType().GetProperties();
- // foreach (PropertyInfo pi in propertys)
- // {
- // colname = "";
- // for (int i = 0; i < dt.Columns.Count; i++)
- // {
- // if (pi.Name.ToLower().Equals(dt.Columns[i].ColumnName.ToLower()))
- // {
- // colname = pi.Name; break;
- // }
- // }
- // if (!string.IsNullOrEmpty(colname))
- // {
- // #region 属性与字段名称一致的进行赋值
- // //if (dt.Rows[j][colname] != DBNull.Value && dt.Rows[j][colname] != null && !object.Equals(dt.Rows[j][colname], null))
- // if (!Convert.IsDBNull(dt.Rows[j][colname]))
- // {
- // try
- // {
- // pi.SetValue(objj, dt.Rows[j][md.FieldMeteDatas[colname].ColumnName], null);
- // }
- // catch (Exception ex)
- // {
- // pi.SetValue(objj, null, null);//为空,但不为Null
- //
- // }
- // }
- // else
- // {
- // pi.SetValue(objj, null, null);//为空,但不为Null
- // }
- // #endregion
- // }
- // if (pi.Name == "PersistType")
- // {
- // pi.SetValue(objj, EntityPersistType.Update, null);
- // }
- // }
- // result.Add(objj);
- // }
- // return result;
- //}
- /// <summary>
- /// 暂时不用
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="dr"></param>
- /// <returns></returns>
- //public static object DataTable2List<T>(IDataReader dr)
- //{
- // T obj = (T)Activator.CreateInstance(typeof(T));
- // MetaData md = MetaDataManager.GetMetaData(typeof(T));
- // if (dr == null) return obj;
- // PropertyInfo[] propertys = obj.GetType().GetProperties();
- // foreach (PropertyInfo pi in propertys)
- // {
- // DataTable MyDataTable = dr.GetSchemaTable();
- // foreach (DataRow row in MyDataTable.Rows)
- // {
- // foreach (DataColumn col in MyDataTable.Columns)
- // {
- // #region 属性与字段名称一致的进行赋值
- // if (pi.Name.ToLower().Equals(row[0].ToString().ToLower()))
- // {
- // //if (dr[row[0].ToString()] != DBNull.Value)
- // //if (dr[row[0].ToString()] != DBNull.Value && dr[row[0].ToString()] != null && !object.Equals(dr[row[0].ToString()], null))
- // if (!Convert.IsDBNull(dr[row[0].ToString()]))
- // {
- // if (pi.PropertyType.ToString().ToLower().Contains("system.int64"))
- // {
- // pi.SetValue(obj, Int64.Parse(dr[row[0].ToString()].ToString()), null);
- // }
- // if (pi.PropertyType.ToString().ToLower().Contains("system.int32"))
- // {
- // pi.SetValue(obj, Int32.Parse(dr[row[0].ToString()].ToString()), null);
- // }
- // else if (pi.PropertyType.ToString().ToLower().Contains("system.datetime"))
- // {
- // pi.SetValue(obj, Convert.ToDateTime(dr[row[0].ToString()].ToString()), null);
- // }
- // else if (pi.PropertyType.ToString().ToLower().Contains("system.boolean"))
- // {
- // pi.SetValue(obj, Convert.ToBoolean(dr[row[0].ToString()].ToString()), null);
- // }
- // else if (pi.PropertyType.ToString().ToLower().Contains("system.single"))
- // {
- // pi.SetValue(obj, Convert.ToSingle(dr[row[0].ToString()].ToString()), null);
- // }
- // else if (pi.PropertyType.ToString().ToLower().Contains("system.double"))
- // {
- // pi.SetValue(obj, Convert.ToDouble(dr[row[0].ToString()].ToString()), null);
- // }
- // else
- // {
- // pi.SetValue(obj, dr[md.FieldMeteDatas[pi.Name].ColumnName], null);
- // }
- // }
- // else
- // pi.SetValue(obj, null, null);//为空,但不为Null
- // }
- // #endregion
- // }
- // }
- // if (pi.Name == "PersistType")
- // {
- // pi.SetValue(obj, EntityPersistType.Update, null);
- // }
- // }
- // return obj;
- //}
- #endregion
- /// <summary>
- /// DataReader转Hashtable
- /// </summary>
- /// <param name="dr"></param>
- /// <returns></returns>
- public static Hashtable ReaderToHashtable(IDataReader dr)
- {
- Hashtable hashtable = new Hashtable();
- while (dr.Read())
- {
- for (int i = 0; i < dr.FieldCount; i++)
- {
- string str = dr.GetName(i).ToLower();
- hashtable[str] = dr[str];
- }
- }
- return hashtable;
- }
- /// <summary>
- /// DataReader转换成单个实体
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="dr"></param>
- /// <returns></returns>
- public static T ReaderToModel<T>(IDataReader dr)
- {
- T local = Activator.CreateInstance<T>();
- while (dr.Read())
- {
- foreach (PropertyInfo info in local.GetType().GetProperties(BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance))
- {
- if (!IsNullOrDBNull(dr[info.Name]))
- {
- info.SetValue(local, HackType(dr[info.Name], info.PropertyType), null);
- }
- }
- }
- return local;
- }
- /// <summary>
- /// 判断是否为空
- /// </summary>
- /// <param name="obj"></param>
- /// <returns></returns>
- public static bool IsNullOrDBNull(object obj)
- {
- return ((obj is DBNull) || string.IsNullOrEmpty(obj.ToString()));
- }
- /// <summary>
- ///
- /// </summary>
- /// <param name="value"></param>
- /// <param name="conversionType"></param>
- /// <returns></returns>
- public static object HackType(object value, Type conversionType)
- {
- if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
- {
- if (value == null)
- {
- return null;
- }
- NullableConverter converter = new NullableConverter(conversionType);
- conversionType = converter.UnderlyingType;
- }
- return Convert.ChangeType(value, conversionType);
- }
- /// <summary>
- /// 返回实体类的泛型列表
- /// </summary>
- /// <typeparam name="T">实体</typeparam>
- /// <param name="SqlTxt">SQL语句</param>
- /// <param name="paras">参数</param>
- /// <returns></returns>
- public static List<T> DrToEnList<T>(IDataReader rdr) where T : new()
- {
- try
- {
- List<T> ts = new List<T>();
- T t = new T();
- Type type = t.GetType();
- PropertyInfo[] pInfos = type.GetProperties();
- while (rdr.Read())
- {
- T mod = new T();
- for (int i = 0; i < rdr.FieldCount; i++)
- {
- string paraName = rdr.GetName(i);
- foreach (PropertyInfo pInfo in pInfos)
- {
- if (string.Compare(pInfo.Name, paraName, true) == 0)
- {
- pInfo.SetValue(mod, DBNull.Value == rdr[i] ? null : rdr[i], null);
- break;
- }
- }
- }
- ts.Add(mod);
- }
- return ts;
- }
- catch (Exception ex)
- {
- return null;
- }
- }
- }
- }
|