ASP. Net uses reflection to realize the method of assigning value to model class

Time:2021-12-8

This paper describes the method of assigning value to model class by using reflection in ASP. Net. Share with you for your reference, as follows:

/// <summary>
///Automatic assignment to model class
/// </summary>
///< param name = "sqlstring" > get the SQL statement to query a model instance < / param >
///< param name = "obj" > model instance object < / param >
/// <returns></returns>
public object selmodel(string sqlstring,object obj)
{
  DataTable dtsell = lcommonbll.GetTable(sqlstring);
  int count = dtsell.Rows.Count;
  if (count == 0)
  {
   return null;
  }
  else
  {
   DataRow dr = dtsell.Rows[0];
   #Region another method
   //foreach (DataColumn col in dr.Table.Columns)
   //{
   // PropertyInfo pt = seller.GetType().GetProperty(col.ColumnName);
   // if (String.IsNullOrEmpty(dr[col.ColumnName].ToString()))
   // {
   //  break;
   // }
   // else
   // {
   //  pt.SetValue(seller, dtsell.Rows[0][0], null);
   // }
   //}
   #endregion
   foreach (System.Reflection.PropertyInfo pi in obj.GetType().GetProperties())
   {
    if (pi.CanWrite)
    {
     try
     {
      if (dtsell.Rows[0][pi.Name]!=null)
      {
       pi.SetValue(obj, dtsell.Rows[0][pi.Name], null);
      }
      else
      {
       pi.SetValue(obj, null, null);
      }
     }
     catch
     {
      pi.SetValue(obj, null, null);
     }
    }
   }
   return obj;
  }
}

. CS call

Seller seller = new Seller();// Entity class
bind BIND = new bind();// Binding method class
seller = (Seller)BIND.selmodel("select * from seller where SID=2", seller);// assignment

For more information about asp.net, readers who are interested can see the special topics on this site:《Summary of asp.net optimization skills》、《Summary of asp.net string operation skills》、《Summary of asp.net operating XML skills》、《Summary of asp.net file operation skills》、《Asp.net Ajax skills summary topic》And《Summary of asp.net cache operation skills》。

I hope this article will help you in ASP. Net programming.