使用反映实现前端WEB窗口控件与后台数据库类对象的动态绑定

using System;
using System.Data;
using System.Reflection;
using System.Configuration;
namespace DbService
{
 /// <summary>
 /// DataObjBinding 的摘要说明。
 /// </summary>
 public class DataObjBinding
 {
  public DataObjBinding()
  {
   //
   // TODO: 在此处添加构造函数逻辑
   //
  }

  public static string [] GetTableColum(string tablename)   //在WEB.config中写入表的字段信息。
  {

   string [] strColumn=ConfigurationSettings.AppSettings[tablename].ToLower().Split('''','''');
   return strColumn;
 }


  /// <summary>
  /// BindDataToClassProperty 的摘要说明。
  /// 数据库表对象到相应的类对象的属性捆定,并将数据记录赋值于相应对象
  /// obj 是前台类对象
  /// TableName  要查询的表名
  /// Condition  要查询的条件
  /// </summary>
  public static void  BindDataToClassProperty(object obj,string TableName, string Condition)
  {
   Type objType =obj.GetType();   //反射当前类的所有属性
   PropertyInfo[] objPropertiesArray = objType.GetProperties();
  
   string RowData="";//用于获得数据库的常量

   DataRow  daiRow=DbAccess.Select(TableName,GetTableColum(TableName),Condition).Tables[0].Rows[0];
   foreach(DataColumn c   in DbAccess.Select(TableName,GetTableColum(TableName),Condition).Tables[0].Columns)
   {
    RowData=daiRow[c.ToString()].ToString();
    foreach (PropertyInfo objProperty in objPropertiesArray)
    {
     // 检查匹配的名称和类型
     if (objProperty.Name.ToUpper() == c.ToString().ToUpper())
     {
      // 将控件的属性设置为业务对象属性值
      try
      {
       if (RowData=="True") RowData="1";  //如果是真假类型
       if (RowData=="False") RowData="0";
       objProperty.SetValue(obj, RowData , null);
       //return true;
      }
      catch
      {
       //return false;
      }
     }
    }
    //return false;
   }
   // return false; 
  
  }


  /// <summary>
  /// BindClassPropertyToData 的摘要说明。
  /// 相应的类对象的属性捆定到数据库表对象,并将数据记录赋值于相应对象
  /// obj 是前台类对象
  /// TableName  要查询的表名
  /// Condition  要查询的条件
  /// </summary>
  public static void BindClassPropertyToData(object obj,string TableName, string Condition)
  {
   Type objType =obj.GetType();   //反射当前类的所有属性
   PropertyInfo[] objPropertiesArray = objType.GetProperties();
  
   int ColumnNum=0; //当前列的序列号
   object[] strValue=new object[GetTableColum(TableName).Length] ; // 初始化要返回的对象 字符串在webconfig中 
   foreach(string  c   in GetTableColum(TableName))
   {
    foreach (PropertyInfo objProperty in objPropertiesArray)
    {
     // 检查匹配的名称和类型
     if (objProperty.Name.ToUpper() == c.ToString().ToUpper())
     {
      // 将控件的属性设置为业务对象属性值
      try
      {
       strValue[ColumnNum]= objProperty.GetValue(obj, null).ToString();
       //return true;
      }
      catch
      {
       //return false;
      }
     }
    }
    ColumnNum++;
    //return false;
   }
  
   DbAccess.Update(TableName,GetTableColum(TableName),strValue,Condition);
  
  } 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值