我通过SqlDataAdapter向我的Sql框发送标准的Sql select语句,然后填充DataSet对象。
我可以访问生成的DataSet中的行,但是如何将DataSet转换为可以返回到MVC View的List。即我假设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的结果集。
提前感谢您的建议......
最佳, 鲍勃
答案 0 :(得分: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")
))
答案 1 :(得分: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);
}
答案 2 :(得分: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);
答案很长(实际上更短)
您的代码可能会改为:
string sqlStr = "SELECT * FROM [RegressionResults].[dbo].[Diff_MasterList] ORDER BY TableName";
return sqlConn.Query<RegresDB_TableName>(sqlStr);
答案 3 :(得分: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>
}