How can I map the results of a sql query onto objects?

后端 未结 7 1651
灰色年华
灰色年华 2021-02-01 20:37

Currently, I am using something like this:

    try
    {
      dr = SQL.Execute(sql);

      if(dr != null) {
         while(dr.Read()) {
           CustomObject         


        
7条回答
  •  北海茫月
    2021-02-01 21:01

    The following function accepts a SQL string and an object, it requires the object to have a property for each column in the select statement. The object must be instantiated.

    public object SqlToSingleObject(string sSql, object o)
    {
        MySql.Data.MySqlClient.MySqlDataReader oRead;
        using (ConnectionHelper oDb = new ConnectionHelper())
        {
            oRead = oDb.Execute(sSql);
            if (oRead.Read())
            {
                for (int i = 0; i < oRead.FieldCount; i++)
                {
                    System.Reflection.PropertyInfo propertyInfo = o.GetType().GetProperty(oRead.GetName(i));
                    propertyInfo.SetValue(o, Convert.ChangeType(oRead[i], propertyInfo.PropertyType), null);
                }
    
                return o;
            }
            else
            {
                return null;
            }
        }
    }
    

提交回复
热议问题