C#用扩展方法进行自动生成添加删除对象转换的功能
public static class ExtendedModel { #region 实体类的增删改查 #region 添加 public static string AddStr(this object t) { StringBuilder strSql = new StringBuilder(); StringBuilder strSql1 = new StringBuilder(); StringBuilder strSql2 = new StringBuilder(); FieldInfo PrimaryKeyInfo = t.GetType().GetField("PrimaryKey"); FieldInfo IdentityStrInfo = t.GetType().GetField("IdentityStr"); string IdentityStr = ""; if (IdentityStrInfo != null) { IdentityStr = IdentityStrInfo.GetValue(t).ToString(); } foreach (var item in t.GetType().GetProperties()) { if (IdentityStr != item.Name && item.PropertyType != typeof(System.Byte[])) { strSql1.Append(item.Name + ","); if (item.PropertyType == typeof(string) || item.PropertyType == typeof(DateTime) || item.PropertyType == typeof(Nullable <DateTime>) || item.PropertyType == typeof(bool)) { if (item.PropertyType == typeof(DateTime) || item.PropertyType == typeof(Nullable<DateTime>)) { DateTime datetime = (DateTime)item.GetValue(t, null); if (datetime>DateTime.Parse("1900-01-01")) { strSql2.Append("'" + datetime.ToString("yyyy-MM-dd HH:mm:ss") + "',"); } else { strSql2.Append("'1900-01-01',"); } } else { strSql2.Append("'" + item.GetValue(t, null) + "',"); } } else { object value = item.GetValue(t, null); if (value != null) { strSql2.Append(value + ","); } else { strSql2.Append("0,"); } } } } strSql.Append("insert into " + t.GetType().Name + "("); strSql.Append(strSql1.ToString().TrimEnd(',')); strSql.Append(")"); strSql.Append(" values ("); strSql.Append(strSql2.ToString().TrimEnd(',')); strSql.Append(")"); return strSql.ToString(); } public static bool Add(this object t) { int istrue = DbHelperSQL.ExecuteSql(AddStr(t)); if (istrue > 0) { return true; } else { return false; } } #endregion #region 删除 public static string DeleteStr<T>(this T t, string Fields) { Type type = t.GetType(); string str = "delete " + type.Name; if (!string.IsNullOrEmpty(Fields)) { str += " where 1=1 "; foreach (string item in Fields.Split(',')) { PropertyInfo info = type.GetProperty(item); str += string.Format(" and {0}='{1}'", info.Name, info.GetValue(t, null)); } } return str; } public static string DeleteWhereStr<T>(this T t, string sqlWhere) where T : new() { Type type = t.GetType(); string str = "delete " + type.Name + " "; if (!string.IsNullOrEmpty(sqlWhere)) { str += sqlWhere; } return str; } public static bool Delete<T>(this T t, string Fields) { int istrue = DbHelperSQL.ExecuteSql(DeleteStr(t, Fields)); if (istrue > 0) { return true; } else { return false; } } public static bool DeleteWhere<T>(this T t, string sqlWhere) where T : new() { int istrue = DbHelperSQL.ExecuteSql(DeleteWhereStr(t, sqlWhere)); if (istrue > 0) { return true; } else { return false; } } #endregion #endregion #region 获取实体类 /// <summary> /// DataRow转换实体类 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="row"></param> /// <returns></returns> public static T ToModel<T>(this DataRow row) where T : new() { T t = new T(); foreach (var item in t.GetType().GetProperties()) { if (row.Table.Columns.IndexOf(item.Name) > -1) { if (row[item.Name] != null && typeof(System.DBNull) != row[item.Name].GetType()) { if (typeof(System.Byte) == row[item.Name].GetType()) { if (item.PropertyType == typeof(System.Nullable<int>) || item.PropertyType == typeof(int)) { item.SetValue(t,Convert.ToInt32(row[item.Name]), null); } } else { item.SetValue(t, Convert.ChangeType(row[item.Name], item.PropertyType), null); } } else if (typeof(System.DateTime) == item.PropertyType) { item.SetValue(t, DateTime.Parse("1999-12-12"), null); } } } return t; } /// <summary> /// DataRow转换实体类 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="row"></param> /// <returns></returns> public static List<T> ToModelList<T>(this DataTable dt) where T : new() { List<T> list = new List<T>(); if (dt.Rows.Count > 0) { foreach (DataRow item in dt.Rows) { list.Add(ToModel<T>(item)); } } return list; } /// <summary> /// 查询Where获取实体类 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="strWhere"></param> /// <returns></returns> public static T Model<T>(this T t, string strWhere) where T : class,new() { string str = "select top 1 * from " + typeof(T).Name + " " + strWhere; DataTable dt = DbHelperSQL.Query(str).Tables[0]; if (dt.Rows.Count > 0) { return ToModel<T>(dt.Rows[0]); } else { return null; } } /// <summary> /// 查询Where获取实体列表 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="strWhere"></param> /// <returns></returns> public static List<T> ModelList<T>(this T t, string strWhere) where T : class,new() { string str = "select * from " + typeof(T).Name + " " + strWhere; DataTable dt = DbHelperSQL.Query(str).Tables[0]; List<T> list = new List<T>(); if (dt.Rows.Count > 0) { foreach (DataRow item in dt.Rows) { list.Add(ToModel<T>(item)); } } return list; } #endregion #region 实体类转换 public static T EntityToT<T, TT>(this TT tt) where T : new() { T t = new T(); List<PropertyInfo> listT = t.GetType().GetProperties().ToList(); List<PropertyInfo> listObj = tt.GetType().GetProperties().ToList(); foreach (var item in listT) { object value = SetPropertyValue(item, listObj, tt); item.SetValue(t, value, null); } return t; } private static object SetPropertyValue(PropertyInfo info, List<PropertyInfo> listObj, object obj) { try { object obValue = null; Type type = info.PropertyType; List<PropertyInfo> objInfo = listObj.Where(c => c.Name.ToLower() == info.Name.ToLower()).ToList(); if (objInfo.Count > 0) { obValue = objInfo[0].GetValue(obj, null); if (type == typeof(decimal) || type == typeof(Decimal)) { if (obValue != null) { obValue = decimal.Parse(obValue.ToString()); } } else if (type == typeof(int)) { if (obValue != null) { obValue = int.Parse(obValue.ToString()); } } else if (type == typeof(DateTime)) { if (obValue != null) { DateTime date = new DateTime(); if (DateTime.TryParse(obValue.ToString(), out date)) { obValue = date; } else { obValue = DateTime.Parse("1999-12-12"); } } else { obValue = DateTime.Parse("1999-12-12"); } } } return obValue; } catch (Exception ex) { throw new Exception(string.Format("实体转换失败")); ; } } #endregion }
调用方法
//datarow转换对象 VWB_Weight upModel = dt.Rows[0].ToModel<VWB_Weight>(); //table转换list List<VWB_Weight> upModel = dt.ToModelList<VWB_Weight>(); upModel.Add(); //一个对象转换另一个对象 AA a = upModel.EntityToT<AA>;
动软生成器模板
<#@ template language="c#" HostSpecific="True" #> <#@ output extension= ".cs" #> <# TableHost host = (TableHost)(Host); host.Fieldlist.Sort(CodeCommon.CompareByintOrder); #> using System; using System.Text; using System.Collections.Generic; using System.Data; namespace <#= host.NameSpace #>.Model<# if( host.Folder.Length > 0) {#>.<#= host.Folder #><# } #> { <# if( host.TableDescription.Length > 0) {#> //<#= host.TableDescription #> <# } #> public class <#= host.GetModelClass(host.TableName) #> { <# foreach (ColumnInfo c in host.Fieldlist) { #>/// <summary> /// <#= string.IsNullOrEmpty(c.Description) ? c.ColumnName : c.Description #> /// </summary> private <#= CodeCommon.DbTypeToCS(c.TypeName) #> _<#= c.ColumnName.ToString().ToLower() #>; public <#= CodeCommon.DbTypeToCS(c.TypeName) #> <#= c.ColumnName #> { get{ return _<#= c.ColumnName.ToString().ToLower()#>; } set{ _<#= c.ColumnName.ToString().ToLower() #> = value; } } <# } #> public string PrimaryKey="<# foreach (ColumnInfo c in host.Keys) { #><#= c.ColumnName #>,<#}#>".TrimEnd(','); public string IdentityStr = "<# for(int i=0;i< host.Fieldlist.Count;i++) { ColumnInfo c = host.Fieldlist[i]; if (c.IsIdentity) {#><#= c.ColumnName#><# if (i< host.Fieldlist.Count-1 ) {#>,<#}#><#}}#>".TrimEnd(','); public string IdentityKey="<#= host.IdentityKey==null?"":host.IdentityKey.ColumnName#>"; } }
像删除和修改的一些代码没有顾得上去添加