publicstaticclassExtendedModel
{#region实体类的增删改查#region添加publicstaticstringAddStr(thisobjectt)
{
StringBuilder strSql=newStringBuilder();
StringBuilder strSql1=newStringBuilder();
StringBuilder strSql2=newStringBuilder();
FieldInfoPRimaryKeyInfo= t.GetType().GetField("PrimaryKey");
FieldInfo IdentityStrInfo= t.GetType().GetField("IdentityStr");stringIdentityStr ="";if(IdentityStrInfo !=null)
{
IdentityStr=IdentityStrInfo.GetValue(t).ToString();
}foreach(varitemint.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{objectvalue = 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(")");returnstrSql.ToString();
}publicstaticboolAdd(thisobjectt)
{intistrue =DbHelperSQL.ExecuteSql(AddStr(t));if(istrue >0)
{returntrue;
}else{returnfalse;
}
}#endregion#region删除publicstaticstringDeleteStr<T>(thisT t,stringFields)
{
Type type=t.GetType();stringstr ="delete"+type.Name;if(!string.IsNullOrEmpty(Fields))
{
str+="where 1=1";foreach(stringiteminFields.Split(','))
{
PropertyInfo info=type.GetProperty(item);
str+=string.Format("and {0}='{1}'", info.Name, info.GetValue(t,null));
}
}returnstr;
}publicstaticstringDeleteWhereStr<T>(thisT t,stringsqlWhere)whereT :new()
{
Type type=t.GetType();stringstr ="delete"+ type.Name +"";if(!string.IsNullOrEmpty(sqlWhere))
{
str+=sqlWhere;
}returnstr;
}publicstaticboolDelete<T>(thisT t,stringFields)
{intistrue =DbHelperSQL.ExecuteSql(DeleteStr(t, Fields));if(istrue >0)
{returntrue;
}else{returnfalse;
}
}publicstaticboolDeleteWhere<T>(thisT t,stringsqlWhere)whereT :new()
{intistrue =DbHelperSQL.ExecuteSql(DeleteWhereStr(t, sqlWhere));if(istrue >0)
{returntrue;
}else{returnfalse;
}
}#endregion#endregion#region获取实体类///<summary>///DataRow转换实体类///</summary>///<typeparam name="T"></typeparam>///<param name="row"></param>///<returns></returns>publicstaticT ToModel<T>(thisDataRow row)whereT :new()
{
T t=newT();foreach(varitemint.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);
}
}elseif(typeof(System.DateTime) ==item.PropertyType)
{
item.SetValue(t, DateTime.Parse("1999-12-12"),null);
}
}
}returnt;
}///<summary>///DataRow转换实体类///</summary>///<typeparam name="T"></typeparam>///<param name="row"></param>///<returns></returns>publicstaticList<T> ToModelList<T>(thisDataTable dt)whereT :new()
{
List<T> list =newList<T>();if(dt.Rows.Count >0)
{foreach(DataRow itemindt.Rows)
{
list.Add(ToModel<T>(item));
}
}returnlist;
}///<summary>///查询Where获取实体类///</summary>///<typeparam name="T"></typeparam>///<param name="strWhere"></param>///<returns></returns>publicstaticT Model<T>(thisT t,stringstrWhere)whereT :class,new()
{stringstr ="select top 1 * from"+typeof(T).Name +""+strWhere;
DataTable dt= DbHelperSQL.Query(str).Tables[0];if(dt.Rows.Count >0)
{returnToModel<T>(dt.Rows[0]);
}else{returnnull;
}
}///<summary>///查询Where获取实体列表///</summary>///<typeparam name="T"></typeparam>///<param name="strWhere"></param>///<returns></returns>publicstaticList<T> ModelList<T>(thisT t,stringstrWhere)whereT :class,new()
{stringstr ="select * from"+typeof(T).Name +""+strWhere;
DataTable dt= DbHelperSQL.Query(str).Tables[0];
List<T> list =newList<T>();if(dt.Rows.Count >0)
{foreach(DataRow itemindt.Rows)
{
list.Add(ToModel<T>(item));
}
}returnlist;
}#endregion#region实体类转换publicstaticT EntityToT<T, TT>(thisTT tt)whereT :new()
{
T t=newT();
List<PropertyInfo> listT =t.GetType().GetProperties().ToList();
List<PropertyInfo> listObj =tt.GetType().GetProperties().ToList();foreach(variteminlistT)
{objectvalue =SetPropertyValue(item, listObj, tt);
item.SetValue(t, value,null);
}returnt;
}privatestaticobjectSetPropertyValue(PropertyInfo info, List<PropertyInfo> listObj,objectobj)
{try{objectobValue =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());
}
}elseif(type ==typeof(int))
{if(obValue !=null)
{
obValue=int.Parse(obValue.ToString());
}
}elseif(type ==typeof(DateTime))
{if(obValue !=null)
{
DateTime date=newDateTime();if(DateTime.TryParse(obValue.ToString(),outdate))
{
obValue=date;
}else{
obValue= DateTime.Parse("1999-12-12");
}
}else{
obValue= DateTime.Parse("1999-12-12");
}
}
}returnobValue;
}catch(Exception ex)
{thrownewException(string.Format("实体转换失败")); ;
}
}#endregion}
调用方法
//datarow转换对象VWB_Weight upModel = dt.Rows[0].ToModel<VWB_Weight>();//table转换listList<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);
#>usingSystem;usingSystem.Text;usingSystem.Collections.Generic;usingSystem.Data;namespace<#= host.NameSpace #>.Model<#if( host.Folder.Length >0) {#>.<#= host.Folder #><# } #>{<#if( host.TableDescription.Length >0) {#>//<#= host.TableDescription #><# } #>publicclass<#= host.GetModelClass(host.TableName) #>{<#foreach(ColumnInfo cinhost.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; }
}<# } #>publicstringPrimaryKey="<# foreach (ColumnInfo c in host.Keys){ #><#= c.ColumnName #>,<#}#>".TrimEnd(',');publicstringIdentityStr ="<# 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(',');publicstringIdentityKey="<#= host.IdentityKey==null?"":host.IdentityKey.ColumnName#>";
}
}
像删除和修改的一些代码没有顾得上去添加