8

我通过 SqlDataAdapter 向我的 Sql 框发送一个标准的 Sql 选择语句,然后填充一个 DataSet 对象。

我可以访问结果数据集中的行,但是如何将数据集转换为可以返回到 MVC 视图的列表。即,我假设 List 对象是处理此问题的最佳方式。

这是我的控制器 C# 代码:

public class QAController : Controller
{

    private readonly static string connString = ConfigurationManager.ConnectionStrings["RegrDBConnection"].ToString();
    private readonly static SqlConnection sqlConn = new SqlConnection(connString);
    private readonly static SqlCommand sqlComm = new SqlCommand();

    public ActionResult Index()
    {
        DbRegressionExec();
        return View();
    }
    public static void DbRegressionExec()
    {
        // SELECT TABLE CONTENTS FROM SQL !!
        RegressDB_TableList regresDB = new RegressDB_TableList();
        string sqlStr = "select * from [RegressionResults].[dbo].[Diff_MasterList] order by TableName";

        // POPULATE DATASET OBJECT
        DataSet ds = new DataSet();
        SqlDataAdapter da = new SqlDataAdapter(sqlStr, sqlConn);
        da.SelectCommand.CommandType = CommandType.Text;
        sqlConn.Open();
        try
        {
            da.Fill(ds, "RegresDB");
        }
        catch (Exception e)
        {
            throw;
        }
        finally
        {
            sqlConn.Close();
        }

       // I can iterate thru rows here, but HOW DO CONVERT TO A LIST OBJECT ????

        int numRows = ds.Tables["RegresDB"].Rows.Count;
        for (int i = 0; i < numRows; i++)
        {
            string tblName = ds.Tables["RegresDB"].Rows[i].Field<string>("TableName");
        }

        //List<RegressDB_TableList> masterList = regresDB.RegresTableList.ToList(); //not working !!
        //var masterList = regresDB.TableName.ToList(); //

    }

}

我可能需要一个简单的类来实现这一点:

namespace RegressionMvc.Models
{
  public class RegresDB_TableName
  {
     public string TableName { get; set; }
  }
  public class RegressDB_TableList
  {
     public List<RegresDB_TableName> RegresTableList { get; set; }
  }

}

最后,我试图找出处理来自 Sql Server 的 DataSet 结果的最佳方法,以及如何将它们返回到 MVC 视图。

我可能会使用 jQuery 和 Json,这意味着只需将数据字段转换为 Json 并返回到 JQuery,但我确信有几种方法可以处理基于 Sql 的结果集。

提前感谢您的建议......

最好的,鲍勃

4

4 回答 4

5

在您的控制器中放置这样的代码

[HttpGet]
public ActionResult View(Modelclass viewmodel)
{
    List<Modelclass> employees = new List<Modelclass>();
    DataSet ds = viewmodel.GetAllAuthors();
    var empList = ds.Tables[0].AsEnumerable().Select(dataRow => new Modelclass{
       AuthorId = dataRow.Field<int>("AuthorId"),
        Fname = dataRow.Field<string>("FName"),
       Lname = dataRow.Field<string>("Lname")
    });
    var list = empList.ToList();



    return View(list);
}

并且在视图中

@{
var gd = new WebGrid(Model, canPage: true, rowsPerPage: 5, selectionFieldName: "selectedRow",ajaxUpdateContainerId: "gridContent");
    gd.Pager(WebGridPagerModes.NextPrevious);}
@gd.GetHtml(tableStyle: "table",

        columns: gd.Columns(
                 gd.Column("AuthorId", "AuthorId"),
                 gd.Column("Fname", " Fname"),
                 gd.Column("Lname", "Lname", style: "description")

 )) 
于 2014-04-09T09:37:57.530 回答
4

如果您坚持使用 DAO,我建议您不要使用 DataSet,而是使用具有SqlDataReader.GetValues()方法速度的强类型类。这是更多的工作,但如果你想要我强烈推荐的强类型类,它必须在某个地方完成。

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<Person> viewModel = new List<Person>();

    // 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);
}
于 2012-10-19T21:58:57.147 回答
4

简短的回答

直接回答你的问题:

var tableList = new List<RegresDB_TableName>();
int numRows = ds.Tables["RegresDB"].Rows.Count;
for (int i = 0; i < numRows; i++)
{
    string tblName = ds.Tables["RegresDB"].Rows[i].Field<string>("TableName");
    tableList.Add(new RegresDB_TableName() { TableName = tblName };
}

return View(tableList);

长答案(实际上更短)

试试dapper-dot-net

您的代码可能会更改为:

string sqlStr = "SELECT * FROM [RegressionResults].[dbo].[Diff_MasterList] ORDER BY TableName";
return sqlConn.Query<RegresDB_TableName>(sqlStr);
于 2012-10-19T22:01:53.087 回答
1

控制器代码

 //pQ is your query you have created 
 //P4DAL is the key name for connection string 

  DataSet ds = pQ.Execute(System.Configuration.ConfigurationManager.ConnectionStrings["Platform4"].ConnectionString);


  //ds will be used below
  //create your own view model according to what you want in your view 
 //VMData is my view model

 var _buildList = new List<VMData>();
            {
                foreach (DataRow _row in ds.Tables[0].Rows)
                {
                    _buildList.Add(new VMData
                    {  
     //chose what you want from the dataset results and assign it your view model fields 

                        clientID = Convert.ToInt16(_row[1]),
                        ClientName = _row[3].ToString(),
                        clientPhone = _row[4].ToString(),
                        bcName = _row[8].ToString(),
                        cityName = _row[5].ToString(),
                        provName = _row[6].ToString(),
                    });



                }

            }

  //you will use this in your view
  ViewData["MyData"] = _buildList;

看法

@if (ViewData["MyData"] != null)
{

    var data = (List<VMData>)ViewData["MyData"];
    <div class="table-responsive">
        <table class="display table"  id="Results">

            <thead>
                <tr>
                    <td>Name</td>
                    <td>Telephone</td>
                    <td>Category </td>
                    <td>City </td>
                    <td>Province </td>

                </tr>
            </thead>

            <tbody>
                @foreach (var item in data)
                {
            <tr>
                <td>@Html.ActionLink(item.ClientName, "_Display", new { id = item.clientID }, new { target = "_blank" })</td>
                <td>@item.clientPhone</td>
                <td>@item.bcName</td>
                <td>@item.cityName</td>
                <td>@item.provName</td>

            </tr>

            }
            </tbody>


        </table>
        </div>
        }
于 2016-08-11T10:09:36.100 回答