C# DataTable与Model互转的示例代码
//////实体转换辅助类 /// publicclassModelConvertHelperwhereT:new() { /// ///List泛型转换DataTable. /// publicDataTableListToDataTable(List items) { vartb=newDataTable(typeof(T).Name); PropertyInfo[]props=typeof(T).GetProperties(BindingFlags.Public|BindingFlags.Instance); foreach(PropertyInfopropinprops) { Typet=GetCoreType(prop.PropertyType); tb.Columns.Add(prop.Name,t); } foreach(Titeminitems) { varvalues=newobject[props.Length]; for(inti=0;i ///model转换DataTable /// /// /// /// publicDataTableModelToDataTable (Titems) { vartb=newDataTable(typeof(T).Name); PropertyInfo[]props=typeof(T).GetProperties(BindingFlags.Public|BindingFlags.Instance); foreach(PropertyInfopropinprops) { Typet=GetCoreType(prop.PropertyType); tb.Columns.Add(prop.Name,t); } varvalues=newobject[props.Length]; for(inti=0;i ///Determineofspecifiedtypeisnullable /// publicstaticboolIsNullable(Typet) { return!t.IsValueType||(t.IsGenericType&&t.GetGenericTypeDefinition()==typeof(Nullable<>)); } /// ///ReturnunderlyingtypeiftypeisNullableotherwisereturnthetype /// publicstaticTypeGetCoreType(Typet) { if(t!=null&&IsNullable(t)) { if(!t.IsValueType) { returnt; } else { returnNullable.GetUnderlyingType(t); } } else { returnt; } } //////DataTable转换泛型List /// ////// publicstaticList DataTableToList(DataTabledt) { //定义集合 List ts=newList (); //获得此模型的类型 Typetype=typeof(T); stringtempName=""; foreach(DataRowdrindt.Rows) { Tt=newT(); //获得此模型的公共属性 PropertyInfo[]propertys=t.GetType().GetProperties(); foreach(PropertyInfopiinpropertys) { tempName=pi.Name;//检查DataTable是否包含此列 if(dt.Columns.Contains(tempName)) { //判断此属性是否有Setter if(!pi.CanWrite)continue; objectvalue=dr[tempName]; if(value!=DBNull.Value) pi.SetValue(t,value,null); } } ts.Add(t); } returnts; } publicstaticTDataTableToModel(DataTabledt) { //定义实体 Tt=newT(); //获得此模型的类型 Typetype=typeof(T); stringtempName=""; foreach(DataRowdrindt.Rows) { //获得此模型的公共属性 PropertyInfo[]propertys=t.GetType().GetProperties(); foreach(PropertyInfopiinpropertys) { tempName=pi.Name;//检查DataTable是否包含此列 if(dt.Columns.Contains(tempName)) { //判断此属性是否有Setter if(!pi.CanWrite)continue; objectvalue=dr[tempName]; if(value!=DBNull.Value) pi.SetValue(t,value,null); } } break; } returnt; } }
以上就是C#DataTable与Model互转的示例代码的详细内容,更多关于C#DataTable与Model互转的资料请关注毛票票其它相关文章!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。