Visual Studio Express 2012 for Web でいってみる 12.ストアドプロシジャを使ってみる(4/6)
前回からの続きです。
№4.コントローラをストアドプロシジャ呼び出しをおこなうように変更(後編)。
さ て、前回は、以前コントローラに記述してた一覧のデータ取得部分を[CarrierRepository]に移植しました。今回はコントローラーを[CarrierRepository]を呼び出すように変更します。
今回もいきなり出来上がりをごらんください。
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Web; using System.Web.Mvc; using Mvc4ApplicationD.Models; using Mvc4ApplicationD.Models.Repositories; namespace Mvc4ApplicationD.Controllers { public class 運送会社Controller : Controller { //この一行は全メソッドがRepositoryに移植できたら削除します。 private NorthwindJEntities db = new NorthwindJEntities(); //データアクセスリポジトリである[Repository]を保持するフィールドを用意 private ICarrierRepository repository; //コンストラクタ public 運送会社Controller() : this(null) { } //コンストラクタまずは引数無し //コンストラクタでCarrierRepositoryを生成 public 運送会社Controller(ICarrierRepository repository)
{ this.repository = (repository ?? new CarrierRepository()); } // // GET: /運送会社/ public ActionResult Index() { //範囲指定情報用変数 int? 運送コードMIN = null; int? 運送コードMAX = null; //ストアドプロシジャのOUTPUTパラメータ用変数。 int dataCount = 0; //ストアドプロシジャを呼び出してデータを取得しmodelを作成 IEnumerable model = this.repository.GetCarriersList
(運送コードMIN, 運送コードMAX, out dataCount); //ストアドプロシジャのOUTPUTパラメータには取得レコード件数がセットされている。 //ViewBagに格納してビューで表示します。 ViewBag.DataCount = dataCount; return View(model); }
Repositoriesにデータベースアクセス部分を映したので、
using Mvc4ApplicationD.Models.Repositories;
の行を追加したほか、以下の処理を追加しています。
private ICarrierRepository repository;
public 運送会社Controller() : this(null) { }
public 運送会社Controller(ICarrierRepository repository)
{this.repository = (repository ?? new CarrierRepository());}
一方、Index メソッドはずいぶんシンプルになった(?)気がします。
ストアドプロシジャのアウトプットパラメータから受け取った[データ件数]をViewBagにセットしてビューで表示させましょう。
ビューの変更は、適当なところ、例えば、以下のように
@model IEnumerable<Mvc4ApplicationD.Models.運送会社ViewModel> @{ ViewBag.Title = "Index"; } <h2>Index</h2> <p> @Html.ActionLink("Create New", "Create") </p> <h3>
データ件数 @ViewBag.DataCount
</h3> <table> <tr> <th> @Html.DisplayNameFor(model => model.運送会社1) </th> <th> @Html.DisplayNameFor(model => model.電話番号) </th> <th></th> </tr> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.運送会社1) </td> <td> @Html.DisplayFor(modelItem => item.電話番号) </td> <td> @Html.ActionLink("Edit", "Edit", new { id=item.運送コード }) | @Html.ActionLink("Details", "Details", new { id=item.運送コード }) | @Html.ActionLink("Delete", "Delete", new { id=item.運送コード }) </td> </tr> } </table>
@ViewBag.DataCount を追加してください。
実行結果は、こんなかんじです。
以上でリスト型(R部分)についてのストアドプロシジャ化の完了です。