ASP.NET MVC从数据库创建模型(Postgres)

时间:2014-06-23 13:08:15

标签: asp.net-mvc postgresql

如果这个问题太愚蠢,请原谅我,但我刚开始学习ASP几天...... 所以我决定制作一些简单的Web应用程序,它将显示数据库中的数据(Postgres)。 使用NpgsqlConnection类连接到DataBase I.我看到很少有教程如何连接到数据库,即here,但在任何地方他们都在使用MSSQL,我无法找到解决方案。 所以我想有一个模型,它将包含所有获取的数据,我将能够像这样迭代:

  <% foreach (var item in Model)
       { %>
    <tr>
        <td><%: item.Title %></td>
        <td><%: String.Format("{0:g}", item.ReleaseDate) %></td>
        <td><%: item.Genre %></td>
        <td><%: item.Rating %></td>
        <td><%: String.Format("{0:F}", item.Price) %></td>
    </tr>
    <% } %>

那么我该怎么做呢? 我想创建类

public class Person{
int id;
string Name;
string Surname;
...
}

接下来创建类型Person的通用列表,并在获取数据后,将所有提取的数据添加到我的列表中。然后以某种方式将此列表作为模型传递。

我认为有更好的方法可以做到。任何建议?

1 个答案:

答案 0 :(得分:0)

不,你已经走上了正轨。

您从教程中看到的主要区别是大多数可能使用实体框架来填充模型。因为你正在使用postgres ...我不会真的建议尝试让实体框架与它一起工作(我听说这是一场噩梦)。如果您愿意,可以使用不同的Orm,或者只使用您可能习惯的连接命令和阅读器。

我这样做的方法是创建一个看起来就像数据库模型的域模型(看起来就像你对Person所做的那样)

从那里你可以在控制器中填充它。

public class PersonController : Controller
{

    //this method will map to the Person/Index route by default
    public ActionResult Index()
    {
        //use your npgsqlconnection right now to populate whatever object you'd like
        List<Person> people = PopulateFromPostgres();

        //here were returning the index view with the model being a list of person
        return View(people)
    }
}

然后在你的视图中(我相信这个例子中的Views / Person / Index.cshtml)

@model List<Person>

<table>
@foreach (var item in Model)
{
    <tr>
        <td>@item.Title</td>
        <td>@String.Format("{0:g}", item.ReleaseDate)</td>
        <td>@item.Genre</td>
        <td>@item.Rating </td>
        <td>string.Format("{0:F}", item.Price)</td>
    </tr>
}
</table>

如果您在此处不了解更具体的区域,请告诉我。