我一直在尝试在我的 ASP.NET MVC 项目中使用预先存在的数据库。我为我的 (Microsoft SQL) 数据库 (.\SQLEXPRESS.Databases) 创建了一个“数据连接”,其中包含表“Test”。该表有两列,“ID (int)”和“name (nvarchar(MAX))”。
在“模型”文件夹中我放了这个新类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
namespace MvcMovie.Models
{
public class Test
{
public int ID { get; set; }
public string name { get; set; }
}
}
然后(在“ Controller ”中)我有一个新的 Controller “HelloWorldController”。在这里我有这个功能:
public ActionResult Index()
{
DataSet data;
DataTable table;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand select = new SqlCommand("SELECT * FROM Test", connection);
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = select;
data = new DataSet();
adapter.Fill(data, "Test");
table = data.Tables[0]; //is the [0] really correct?
}
return View(/* HOW DO I GET THE TABLE TO THE VIEW? */);
}
现在我想在我的“Index.cshtml”文件(在“ View ”中)中显示表格的行。如何将表从 Controller 获取到 View ?我发现的是“@model”和“IEnumerable”,但这不起作用,因为我无法转换我的表。
@model IEnumerable<MyProject.Models.Test>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@foreach (var item in Model) {
<p>blaaaah</p>
}
现在有三个问题:
1.我做错了什么吗? (DB-Access的方法,..)
2. 有更简单的方法吗? (没有所有适配器,..东西)
3. 如果 !1&&!2,我如何让它工作? (获取 View 文件以“了解”我的表)
谢谢你的帮助,
问候,
卡巴
最佳答案
我建议您使用 View 模型并摆脱数据集和表。让我们忘记那些数据类型。它们是遗产。
例如,您可以有一个方法(您最终会将其外部化到存储库中,以避免因数据库访问而污染您的 Controller 代码):
public IEnumerable<Test> GetTests()
{
using (var conn = new SqlConnection(connectionString))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "SELECT ID, name FROM Test";
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
yield return new Test
{
ID = reader.GetInt32(reader.GetOrdinal("ID")),
name = reader.GetString(reader.GetOrdinal("name")),
}
};
}
}
}
然后是你的 Controller Action :
public ActionResult Index()
{
IList<Test> tests = GetTests().ToList();
return View(tests);
}
到目前为止一切顺利。最后相应的强类型 View 来显示结果:
@model IList<Test>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
</thead>
<tbody>
@for (var i = 0; i < Model.Count; i++)
{
<tr>
<td>@Html.DisplayFor(x => x[i].ID)</td>
<td>@Html.DisplayFor(x => x[i].name)</td>
</tr>
}
</tbody>
</table>
或使用 WebGrid
如果您愿意,可以提供帮助:
@model IList<Test>
@{
var grid = new WebGrid(Model);
}
@grid.GetHtml()
关于c# - ASP.NET MVC 数据库访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10415846/