欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

.net c#将数据库数据对象转换为实体值对象

程序员文章站 2022-07-11 09:14:34
using System; using System.Data; namespace Sunlib { public static class DataHelper { //将数据库数据对象转换为实体值对象 //T:要转换的类型 //columnName:列名 //defValue:默认值 publ ......

using system;

using system.data;

namespace sunlib

{

    public static class datahelper

    {

      //将数据库数据对象转换为实体值对象

      //t:要转换的类型

      //columnname:列名

      //defvalue:默认值

      public static t tovalue<t>(datarow dr, string columnname,t defvalue)

      {

          if(dr.table.columns.contains(columnname)==true)

           {

              if(dr[columnname]!=dbnull.value&&string.isnullorwhitespace(dr[columnname].tostring())==false)

              {

                  return (t)(convert.changetype(dr[columnname], typeof(t)))

              }

                //如果获取的字段值为空,就返回默认值

                 return defvalue;

           }

           //调用函数tovalue

           public void update()

            {

              //省略获取table数据部分代码

              datarow dr=ds.tables[0].rows[0];

              //获取数据表对应字段数值,tovalue默认值很关键,默认值可以决定获取的类型

              string meterno=tovalue(dr,"meterno","");//string类型默认值加双引号

              decimal insideno=tovalue(dr,"insideno",0m);//decimal默认值可以设为0m或者decimal类型值

              datetime reading=tovalue<datetime>(dr,"reading",datetime.now);//datetime默认值可以设为当前值;只要默认值类型设置正确,<>可以去掉

            }          

      }

    }  

 

 

 

 

 

 

 

}