asp. net method of assigning value to model class using reflection

  • 2021-09-12 00:58:39
  • OfStack

In this paper, the method of asp. net using reflection to assign value to model class is described. Share it for your reference, as follows:


/// <summary>
///  To model Class automatic assignment 
/// </summary>
/// <param name="sqlstring"> Get a query 1 A model Instance of the sql Statement </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 1 Methods 
   //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 readers interested in asp. net, please check the topics on this site: "asp. net Optimization Skills Summary", "asp. net String Operation Skills Summary", "asp. net Operation XML Skills Summary", "asp. net File Operation Skills Summary", "asp. net ajax Skills Summary" and "asp. net Cache Operation Skills Summary".

I hope this paper is helpful to everyone's asp. net programming.


Related articles: