How to return a DataSet to a View

前端 未结 4 422
天命终不由人
天命终不由人 2021-01-12 07:55

I am sending a standard Sql select statement to my Sql box via the SqlDataAdapter, then populating a DataSet object.

I can access the rows in the resulting DataSet,

4条回答
  •  攒了一身酷
    2021-01-12 08:12

    If you're stuck with using DAO, I would suggest not using a DataSet and instead use a strongly typed class with the speed of SqlDataReader.GetValues() method. It's more work, but it has to be done somewhere if you want strongly typed classes which I would highly recommend.

    public class Person
    {
      public Person(Object[] values]
      {
        this.FirstName = (string)values[0];
        this.LastName = (string)values[1];
        this.Birthday = (DateTime)values[2];
        this.HasFavoriteColor = (bool)values[3];
      }
    
      public string FirstName { get; private set; }
      public string LastName { get; private set; }
      public DateTime Birthday { get; private set; }
      public bool HasFavoriteColor { get; private set; }
    }
    
    public static void DbRegressionExec()
    {
        List viewModel = new List();
    
        // SELECT TABLE CONTENTS FROM SQL !!
        RegressDB_TableList regresDB = new RegressDB_TableList();
        string sqlStr = "select
            FirstName
            ,LastName
            ,Birthday
            ,HasFavoriteColor
          from [RegressionResults].[dbo].[Diff_MasterList] 
          order by TableName";
    
        // POPULATE VIEWMODEL OBJECT
        sqlConn.Open();
    
        try
        {
          using (SqlCommand com = new SqlCommand(sqlStr, sqlConn))
          {
            using (SqlDbReader reader = com.ExecuteReader())
            {
              while(reader.Read())
              {
                viewModel.Add(new Person(com.GetValues()));
              }
            }
          }
        }
        catch (Exception e)
        {
            throw;
        }
        finally
        {
            sqlConn.Close();
        }
    
        return this.View(viewModel);
    }
    

提交回复
热议问题