如何在Asp.net MVC 5中不使用实体框架填充模型

5
注意:这个问题会在那些不知道实体框架并直接开始学习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>

1
还有其他可能会出现问题的地方吗?只是好奇想知道。 - NullPoiиteя
我真的不太确定我现在明白你在问什么了。起初似乎你是在寻找如何编写一个动作,但现在看起来你已经基本完成了一个。最新编辑之后,你有什么问题? - Matthew Haugen
你是对的马修,事实上这个问题被搁置了,所以我也在问题中添加了我的答案。 - hellowahab
2个回答

8

你已经接近成功了。你的控制器应该是这样的:

public ActionResult Index()
{
  List<BillingValidation> list = new List<BillingValidation>();
  try
  {
    // runs stored procedure and returns data to main page
    using (SqlConnection con = new SqlConnection())
    {
      String sql = @"yourquery";
      con.ConnectionString = @"yourconnection"

      DataTable dt = new DataTable();
      SqlDataAdapter da = new SqlDataAdapter();
      da.SelectCommand = new SqlCommand(sql, con);

      da.Fill(dt);

      foreach (DataRow row in dt.Rows)
      {
        var bilVal = new BillingValidation();
        bilVal.Total = row["Total"].ToString();
        bilVal.Section = row["Section"].ToString();
        bilVal.Details = row["Details"].ToString();
        list.Add(bilVal);
      }
    }
    return View(list);
  }
}

对于长这样的模型:

using System.Data.Entity;
using System.Security.Claims;
using System.ComponentModel.DataAnnotations;

namespace SO_GUI.Models
{    
    public class BillingValidation
    {

        [Key]
        public string Section { get; set; }

        public string Details { get; set; }

        public string Total { get; set; }
    }    
}

您的视图可能会像这样:

@model IEnumerable<SO_GUI.Models.BillingValidation>

@{
    ViewBag.Title = "Index";
}

<h2>Billing Validation</h2>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Section)
        </th> 
        <th>
            @Html.DisplayNameFor(model => model.Details)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Total)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Section)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Details)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Total)
        </td>
    </tr>
}
</table>

希望这有所帮助。

4
在一个操作中,你可以做任何想做的事情。它只是一个方法,类似于其他方法,但有一定的合理性限制。如果你不使用MVC,你将如何获取数据?
听起来你正在寻找使用ADO.net、类似于SqlConnection和SqlCommand的类的东西。
使用ADO.net相当简单,尽管有时会有点混乱,所以我会倾向于将其拆分成自己的层。但无论如何,编写该代码超出了这个问题的范围,根据你提供的信息询问如何做太过广泛。
简而言之,在那个方法中,你可以做任何你想做的事情。忽略数据访问部分,你可以从这里开始构建。
public ActionResult Index()
{
    var transactions = new List<Portal.Models.TransactionModels>();

    transactions.Add(new Portal.Models.TransactionModels{
        id = "1",
        statusId = 4
    })
    transactions.Add(new Portal.Models.TransactionModels{
        id = "2",
        statusId = 3
    })

    return View(transactions);
}

如果您将它放进去,您的视图应该会被这两行假数据填充。

谢谢,马修。让我尝试一下。我将使用简单的Ado.net获取包含值的数据表,并尝试使用该数据表构建交易列表。 - hellowahab

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接