注意:这个问题会在那些不知道实体框架并直接开始学习ASP.NET MVC 5的开发者心中产生。一旦你开始学习一件新事物,理解多个新概念就会变得困难。这个问题将帮助新开发者利用他们现有的ADO.NET知识直接开始使用MVC。
这是我的观点:-
我一直在尝试将ASP.NET MVC 5与我的现有数据库配合使用。我不想使用实体框架来填充模型。如何在不使用任何dbcontext的情况下填充我的模型?如何从数据库中提取数据并放入模型中? 下面是我的控制器Action代码:
public ActionResult Index()
{
/* WHAT TO DO HERE TO LOAD THE TRANSACTIONS? This part is resolved in following lines*/
/* I have used following code to get it using the direct db connection */
var transactions = new List<Portal.Models.TransactionModels>();
var connectionString = "server=yourserver;database=yourdatabase;uid=youruid;pwd=yourpwd";
MySqlConnection oMySqlConnection = new MySqlConnection(connectionString);
oMySqlConnection.Open();
MySqlCommand oMySqlCommand = new MySqlCommand("Select * from yourtable;", oMySqlConnection);
MySqlDataReader oMySqlDataReader = oMySqlCommand.ExecuteReader();
while (oMySqlDataReader.Read())
{
transactions.Add(new Portal.Models.TransactionModels
{
transaction_id = oMySqlDataReader["transaction_id"].ToString()
});
}
oMySqlConnection.Close();
return View(transactions);
return View();
}
这是我的模型:
public class TransactionModels
{
public virtual string id{ get; set;}
public virtual int statusid { get; set; }
}
这是我的观点:-
@model IEnumerable<Portal.Models.TransactionModels>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.id)
</th>
<th>
@Html.DisplayNameFor(model => model.statusid)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.id)
</td>
<td>
@Html.DisplayFor(modelItem => item.statusid)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
</tr>
}
</table>