简体   繁体   English

ASP.NET MVC数据库访问

[英]ASP.NET MVC Database access

I've been trying to use a preexisting database in my ASP.NET MVC project. 我一直在尝试在ASP.NET MVC项目中使用预先存在的数据库。 I create a "Data Connection" to my (Microsoft SQL)Database (".\\SQLEXPRESS.Databases"), which has the table "Test". 我为我的(Microsoft SQL)数据库(“。\\ SQLEXPRESS.Databases”)创建了一个“数据连接”,其中包含表“Test”。 This table has two columns, "ID (int)" and "name (nvarchar(MAX))". 该表有两列,“ID(int)”和“name(nvarchar(MAX))”。

In the "Models" folder I put this new class: 在“Models”文件夹中,我放了这个新类:

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; }
    }
}

Then (in "Controllers") I have a new Controller, "HelloWorldController". 然后(在“控制器”中)我有一个新的Controller,“HelloWorldController”。 In this I have this function: 在这我有这个功能:

    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? */);
    }

Now I would like to display the rows of the table in my "Index.cshtml" file (in "Views"). 现在我想在我的“Index.cshtml”文件中显示表格的行(在“视图”中)。 How do I get the table from the Controller to the view? 如何从Controller获取表到视图? What I found was with "@model" and "IEnumerable", but that does not work, since I cannot convert my table. 我发现的是“@model”和“IEnumerable”,但这不起作用,因为我无法转换我的表。

@model IEnumerable<MyProject.Models.Test>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

@foreach (var item in Model) {
    <p>blaaaah</p>
}

Now there are three questions: 现在有三个问题:
1. Am I doing something completely wrong? 我做错了什么吗? (Method of DB-Access,..) (DB访问方法,......)
2. Is there an easier way to do this? 2.有更简单的方法吗? (Without all adapter,.. stuff) (没有所有适配器,..东西)
3. If !1&&!2, How do I get it to work? 3.如果!1 &&!2,我如何让它工作? (Get the view file to "know" my table) (获取视图文件以“知道”我的表)

Thanks for help, 感谢帮助,
Regards, 问候,
Caba 卡巴

I'd recommend you using view models and get rid of DataSets and Tables. 我建议你使用视图模型并摆脱DataSet和Tables。 Let's forget about those data types. 让我们忘掉那些数据类型。 They are legacy. 他们是遗产。

For example you could have a method (which you would eventually externalize into a repositorhy to avoid polluting your controller code with database access): 例如,您可以使用一个方法(最终将其外部化为repositorhy以避免使用数据库访问来污染控制器代码):

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")),
                }
            };
        }
    }

}

and then your controller action: 然后你的控制器动作:

public ActionResult Index()
{
    IList<Test> tests = GetTests().ToList();
    return View(tests);
}

So far so good. 到现在为止还挺好。 Finally the corresponding strongly typed view to display the results: 最后相应的强类型视图显示结果:

@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>

or use the WebGrid helper if you prefer: 或者如果您愿意,可以使用WebGrid助手:

@model IList<Test>
@{
    var grid = new WebGrid(Model);
}
@grid.GetHtml()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM