using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Reflection; using System.Text; using System.Threading; using System.Threading.Tasks; using WebAPI.Utility; namespace WebAPI.Controllers.SCGL.日计划管理 { public static class DataHelper { public static List ToModelList(this DataSet ds) where T : new() { try { List list = new List(); if (ds.Tables[0].Rows.Count > 0) { foreach (DataRow row in ds.Tables[0].Rows) { list.Add(row.Put(new T())); } } return list; } catch (Exception ex) { throw; } } public static List ToModelList(this DataTable dt) where T : new() { try { List list = new List(); if (dt.Rows.Count > 0) { foreach (DataRow row in dt.Rows) { list.Add(row.Put(new T())); } } return list; } catch (Exception ex) { throw; } } /// /// 返回一条数据的Model /// /// Model类型 /// Model类型 /// /// public static T ToModel(DataSet ds) where T : new() { try { T m = new T(); if (ds.Tables[0].Rows.Count > 0) { m = ds.Tables[0].Rows[0].Put(new T()); } return m; } catch (Exception) { return default(T); //throw; } } public static T Put(this DataRow row, T entity) where T : new() { if (entity == null) { entity = new T(); } Type type = typeof(T); PropertyInfo[] pi = type.GetProperties(); foreach (PropertyInfo item in pi) { int index = row.Table.Columns.IndexOf(item.Name); if (index != -1) { if (row[item.Name] != null && row[item.Name] != DBNull.Value) { if (item.PropertyType == typeof(DateTime)) { //如果对日期格式有特殊要求 可以在这里转换 item.SetValue(entity, Convert.ToDateTime(row[item.Name].ToString()), null); } else { item.SetValue(entity, ChangeType(row[item.Name], item.PropertyType), null); } } } } return entity; } public static object ChangeType(object obj, Type conversionType) { return ChangeType(obj, conversionType, Thread.CurrentThread.CurrentCulture); } public static object ChangeType(object obj, Type conversionType, IFormatProvider provider) { #region Nullable Type nullableType = Nullable.GetUnderlyingType(conversionType); if (nullableType != null) { if (obj == null) { return null; } return Convert.ChangeType(obj, nullableType, provider); } #endregion if (typeof(System.Enum).IsAssignableFrom(conversionType)) { return Enum.Parse(conversionType, obj.ToString()); } return Convert.ChangeType(obj, conversionType, provider); } public static string ToListParam(this List list) { string str = string.Empty; foreach (var item in list) { str += $"'{item}',"; } str = str.TrimEnd(','); str = $"({str})"; return str; } public static string GetUpdateStr(string table, Dictionary dic, string condition) { var strSet = string.Empty; foreach (var item in dic) { var type = Util.GetObjectType(item.Value); switch (type) { case "string": case "date": strSet += $" {item.Key}='{item.Value}' "; break; default: strSet += $" {item.Key}={item.Value} "; break; } } return $"update {table} set {strSet} where 1=1 {condition}"; } } }