实体框架在视图中显示SQL查询结果

时间:2014-04-27 07:49:22

标签: c# sql entity-framework visual-studio asp.net-mvc-5

所以我有一个视图,我试图在一个帐户上显示所有交易。

这是SQL

    Select Distinct TransactionAmount,DateOfTransaction
    From BankAccountModels
    Inner Join TransactionModels on BankAccountModels.AccountID=TransactionModelID

我正试图在我的视图中显示结果

这是我的控制器

    // GET: /BankAccount/Details/5
    public ActionResult Details(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        BankAccountModel bankaccountmodel = db.BankAccountModels.Find(id);
        if (bankaccountmodel == null)
        {
            return HttpNotFound();
        }
       // string query = "Select Distinct TransactionAmount,DateOfTransaction From BankAccountModels Inner Join TransactionModels on BankAccountModels.AccountID=TransactionModelID";
       // IEnumerable<BankAccountModel> data = db.Database.SqlQuery<BankAccountModel>(query);
        return View(bankaccountmodel);
    }

这是我目前的观点

    @model Bank7round2.Models.BankAccountModel

    @{
        ViewBag.Title = "Details";
    }

    <h2>Details</h2>

    <div>
        <h4>BankAccountModel</h4>
        <hr />
        <dl class="dl-horizontal">
            <dt>
                @Html.DisplayNameFor(model => model.Balance)
            </dt>

            <dd>
                @Html.DisplayFor(model => model.Balance)
            </dd>

            <dt>
                @Html.DisplayNameFor(model => model.UserName)
            </dt>

            <dd>
                @Html.DisplayFor(model => model.UserName)
            </dd>

        </dl>
    </div>
    <p>
        @Html.ActionLink("Edit", "Edit", new { id = Model.AccountID }) |
        @Html.ActionLink("Back to List", "Index")
    </p>

我该怎么做?

1 个答案:

答案 0 :(得分:0)

如果传递给视图的模型实现了IEnumerable,那么你可以这样做:

<table>
    <tr>
        <th>Transaction ID</th>
        <th>Amount</th>
    </tr>

@foreach(var transaction in YourTransactionModel)
{
    <tr>
        <td>@transaction.ID</td>
        <td>@transaction.Amount</td>
    </tr>
}

</table>