目錄 1.倉儲模式在MVC應用程式中的使用 2.泛型倉儲模式在MVC應用程式中的使用 3.MVC Code-First和倉儲模式的應用 4.待續.... 附上源代碼:https://github.com/caofangsheng93/CaoDanDeGit 這篇文章中,我會解釋倉儲模式在MVC程式中 ...
目錄
- 1.倉儲模式在MVC應用程式中的使用
- 2.泛型倉儲模式在MVC應用程式中的使用
- 3.MVC Code-First和倉儲模式的應用
- 4.待續....
附上源代碼:https://github.com/caofangsheng93/CaoDanDeGit
這篇文章中,我會解釋倉儲模式在MVC程式中的使用。
首先,我們需要理解什麼是倉儲模式【repository Pattern】,來看看下麵的圖片
沒有使用倉儲模式的MVC應用程式:
使用了倉儲模式的MVC應用程式:
倉儲模式,是一個抽象層,它將資料庫的訪問邏輯,映射到實體的訪問邏輯。
下麵,我們來看做一個應用程式,來體驗一下倉儲模式吧。
首先,打開VS2013,找到--“文件”--->>"新建"---->>"項目"
選擇“ASp.NET Web 應用程式”,輸入名稱,選擇項目存放的位置,點擊”確定“按鈕
在彈出來的對話框中,選擇“MVC”模板,然後點擊“更改身份驗證”,選擇“無身份驗證”,點擊“確定”。
接下來就生成了項目模板:
好了,第一階段的工作就完成了。新建一個MVC程式。
現在開始第二階段的任務:
這篇文章中,我打算使用EF Model First來完成。
首先,我來新建一個資料庫,還有數據表,打開SQL 2008
這樣就創建好了資料庫和數據表,
USE master GO IF EXISTS (SELECT * FROM sysdatabases WHERE name='EmployeeManagementDB') DROP DATABASE EmployeeManagementDB GO CREATE DATABASE EmployeeManagementDB GO USE EmployeeManagementDB GO IF EXISTS(SELECT * FROM sysobjects WHERE name='Employee') DROP TABLE Employee GO CREATE TABLE Employee ( ID INT NOT NULL PRIMARY KEY IDENTITY(1,1), Name NVARCHAR(50) NOT NULL, Age INT NOT NULL, Email NVARCHAR(200) NOT NULL )SQL腳本
現在就開始下麵的步驟吧,右鍵點擊項目,選擇添加-->新建項
在演出來的對話框中,選擇Visual C#-->ADO.NET實體數據模型-->輸入名稱--->添加
然後在彈出開的對話框中,選擇第一個-->>>”來自資料庫的EF設計器“,點擊下一步:
在彈出來的對話框中,選擇--“新建連接”,然後點擊下一步
在出來的對畫框中,輸入信息,連接上我們剛纔創建的資料庫。測試通過之後,點擊確定。
好了,截圖截的差不多了,現在在我們項目中添加一個文件夾DAL,然後在往這個文件夾中,添加一個介面-->>>IEmployeeRepository.cs.
現在就是Coding了,介面中的代碼是:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RepositoryPatternMVCWithEntityFramework.DAL { interface IEmployeeRepository<T> where T:class { /// <summary> /// 獲取所有的Employee /// </summary> /// <returns></returns> IEnumerable<T> GetAllEmployee(); /// <summary> /// 根據ID獲取 /// </summary> /// <param name="id"></param> /// <returns></returns> T GetEmployeeById(object id); /// <summary> /// 增加 /// </summary> /// <param name="obj"></param> void InsertEmployee(T obj); /// <summary> /// 更新 /// </summary> /// <param name="obj"></param> void UpdateEmployee(T obj); /// <summary> /// 刪除 /// </summary> /// <param name="id"></param> void DeleteEmployee(object id); /// <summary> /// 保存 /// </summary> void Save();
void Dispose(); } }
然後在DAL文件夾下,在添加一個類EmployeeRepository ,代碼如下:
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace RepositoryPatternMVCWithEntityFramework.DAL { public class EmployeeRepository:IEmployeeRepository<Employee>,IDisposable { private EmployeeManagementDBEntities context; public EmployeeRepository(EmployeeManagementDBEntities context) { this.context = context; } public IEnumerable<Employee> GetAllEmployee() { return context.Employees.ToList(); } public Employee GetEmployeeById(object id) { return context.Employees.Find(id); } public void InsertEmployee(Employee obj) { context.Employees.Add(obj); } public void UpdateEmployee(Employee obj) { context.Entry(obj).State = System.Data.EntityState.Modified; } public void DeleteEmployee(object id) { Employee em= context.Employees.Find(id); context.Employees.Remove(em); } public void Save() { context.SaveChanges(); } private bool disposed = false; protected virtual void Dispose(bool disposing) { if (!this.disposed) { if (disposing) { context.Dispose(); } } this.disposed = true; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } } }
然後,在控制器文件夾下,添加一個控制器EmployController,空的。。
然後,先暫停一下,我這邊打算使用分頁,引用pageList.mvc
現在控制器的代碼:
using RepositoryPatternMVCWithEntityFramework.DAL; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; //分頁引用 using PagedList; namespace RepositoryPatternMVCWithEntityFramework.Controllers { public class EmployeeController : Controller { private IEmployeeRepository<Employee> employeeRepository; public EmployeeController() { this.employeeRepository = new EmployeeRepository(new EmployeeManagementDBEntities()); } // GET: Employee public ViewResult Index(string sortOrder, string currentFilter, string searchString, int? page) { ViewBag.CurrentSort = sortOrder; ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "ID" : ""; if (searchString != null) { page = 1; } else { searchString = currentFilter; } ViewBag.CurrentFilter = searchString; var employees = from s in employeeRepository.GetAllEmployee() select s; if (!String.IsNullOrEmpty(searchString)) { employees = employees.Where(s => s.Name.ToUpper().Contains(searchString.ToUpper()) || s.Name.ToUpper().Contains(searchString.ToUpper())); } switch (sortOrder) { case "ID": employees = employees.OrderByDescending(s => s.ID); break; case "Name": employees = employees.OrderBy(s => s.Name); break; case "Email": employees = employees.OrderBy(s => s.Email); break; case "Age": employees = employees.OrderBy(s => s.Age); break; default: employees = employees.OrderBy(s => s.ID); break; } int pageSize = 5; int pageNumber = (page ?? 1); return View(employees.ToPagedList(pageNumber, pageSize)); } // GET: /Employee/Details/5 public ViewResult Details(int id) { Employee emp = employeeRepository.GetEmployeeById(id); return View(emp); } // GET: /Employee/Create public ActionResult Create() { return View(); } // POST: /Employee/Create [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create( [Bind(Include = "Name, Email")] Employee emp) { try { if (ModelState.IsValid) { employeeRepository.InsertEmployee(emp); employeeRepository.Save(); return RedirectToAction("Index"); } } catch (Exception ex) { ModelState.AddModelError(string.Empty, "Some Error Occured."); } return View(emp); } // GET: /Employee/Edit/5 public ActionResult Edit(int id) { Employee emp = employeeRepository.GetEmployeeById(id); return View(emp); } // POST: /Employee/Edit/5 [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit(Employee emp) { try { if (ModelState.IsValid) { employeeRepository.UpdateEmployee(emp); employeeRepository.Save(); return RedirectToAction("Index"); } } catch (Exception ex) { ModelState.AddModelError(string.Empty, "Some error Occured."); } return View(emp); } // GET: /employee/Delete/5 public ActionResult Delete(bool? saveChangesError = false, int id = 0) { if (saveChangesError.GetValueOrDefault()) { ViewBag.ErrorMessage = "Some Error Occured."; } Employee emp = employeeRepository.GetEmployeeById(id); return View(emp); } // POST: /Employee/Delete/5 [HttpPost] [ValidateAntiForgeryToken] public ActionResult Delete(int id) { try { Employee emp = employeeRepository.GetEmployeeById(id); employeeRepository.DeleteEmployee(id); employeeRepository.Save(); } catch (Exception ex) { return RedirectToAction("Delete", new { id = id, saveChangesError = true }); } return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { employeeRepository.Dispose(); base.Dispose(disposing); } } }
Index視圖:
@using PagedList.Mvc; @model PagedList.IPagedList<Employee> @*分頁CSS*@ <link href="~/Content/PagedList.css" rel="stylesheet" type="text/css" /> 備註一下,這個是添加pagedList分頁之後,自動添加進來的。 @{ ViewBag.Title = "Employee Management System"; } <h2>Employee Management System</h2> @using (Html.BeginForm("Index", "Employee", FormMethod.Get)) { <p style="background-color:red; color:white; font-size:16pt; padding:10px;"> Search Employee By Name: @Html.TextBox("SearchString", ViewBag.CurrentFilter as string) <input type="submit" value="Search" /> @Html.ActionLink("Add New Employee", "Create") </p> } <table style="background-color:white;"> <tr> <th></th> <th style="width: 100px;"> @Html.ActionLink("Emp ID", "Index", new { sortOrder = ViewBag.NameSortParm, currentFilter = ViewBag.CurrentFilter }) </th> <th> @Html.ActionLink("Name", "Index", new { sortOrder = ViewBag.NameSortParm, currentFilter = ViewBag.CurrentFilter }) </th> <th> Email </th> <th> Age </th> <th style="width: 150px;"></th> </tr> @foreach (var item in Model) { <tr> <td></td> <td> @Html.DisplayFor(modelItem => item.ID) </td> <td style="width:130px;"> @Html.DisplayFor(modelItem => item.Name) </td> <td> @Html.DisplayFor(modelItem => item.Email) </td> <td style="width:140px;"> @Html.DisplayFor(modelItem => item.Age) </td> <td style="width:270px;"> @Html.ActionLink("Edit", "Edit", new { id = item.ID }) | @Html.ActionLink("Details", "Details", new { id = item.ID }) | @Html.ActionLink("Delete", "Delete", new { id = item.ID }) </td> </tr> } </table> <br /> <div style="background-color:orange; padding-left:15px; padding-top:10px;"> Showing Records @(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of @Model.PageCount //備註一下:這裡的Pagecount ,PageNumber也都是///分頁控制項中的 @Html.PagedListPager(Model, page => Url.Action("Index", new { page, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter })) </div>
Create視圖:
@model Employee <script src="~/Scripts/jquery-1.7.1.min.js"></script> <script src="~/Scripts/jquery.validate.min.js"></script> <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script> @using (Html.BeginForm()) { @Html.AntiForgeryToken() @Html.ValidationSummary(true) <fieldset> <legend>Employee</legend> <div class="editor-label"> @Html.LabelFor(model => model.Name) </div> <div class="editor-field"> @Html.EditorFor(model => model.Name) @Html.ValidationMessageFor(model => model.Name) </div> <div class="editor-label"> @Html.LabelFor(model => model.Email) </div> <div class="editor-field"> @Html.EditorFor(model => model.Email) @Html.ValidationMessageFor(model => model.Email) </div> <div class="editor-label"> @Html.LabelFor(model => model.Age) </div> <div class="editor-field"> @Html.EditorFor(model => model.Age) @Html.ValidationMessageFor(model => model.Age) </div> <p> <input type="submit" value="Create" /> </p> </fieldset> } <div> @Html.ActionLink("Back to List", "Index") </div>
Edit視圖:
@model Employee <script src="~/Scripts/jquery-1.7.1.min.js"></script> <script src="~/Scripts/jquery.validate.min.js"></script> <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script> <h2>Edit Employee information</h2> @using (Html.BeginForm()) { @Html.AntiForgeryToken() @Html.ValidationSummary(true) <table> <tr> <td>@Html.LabelFor(model => model.ID)</td> <td> @Html.EditorFor(model => model.ID, new { disabled = "disabled", @readonly = "readonly" }) @Html.ValidationMessageFor(model => model.ID) </td> </tr> <tr> <td> @Html.LabelFor(model => model.Name) </td> <td> @Html.EditorFor(model => model.Name) @Html.ValidationMessageFor(model => model.Name) </td> </tr> <tr> <td>@Html.LabelFor(model => model.Email)</td> <td> @Html.EditorFor(model => model.Email) @Html.ValidationMessageFor(model => model.Email) </td> </tr> <tr> <td>@Html.LabelFor(model => model.Age)</td> <td> @Html.EditorFor(model => model.Age) @Html.ValidationMessageFor(model => model.Age) </td> </tr> <tr style="background-color: orange; padding: 25px;"> <td></td> <td> <input type="submit" value="Save" /> @Html.ActionLink("Back to List", "Index") </td> </tr> </table> }
delete視圖:
@model Employee <h3>Are you sure you want to delete this?</h3> <table> <tr> <td>@Html.DisplayNameFor(model => model.ID)</td> <td>@Html.DisplayFor(model => model.ID)</td> </tr> <tr> <td>@Html.DisplayNameFor(model => model.Name)</td> <td>@Html.DisplayFor(model => model.Name)</td> </tr> <tr> <td>@Html.DisplayNameFor(model => model.Email)</td> <td>@Html.DisplayFor(model => model.Email)</td> </tr> <tr> <td>@Html.DisplayNameFor(model => model.Age)</td> <td>@Html.DisplayFor(model => model.Age)</td> </tr> </table> @using (Html.BeginForm()) { @Html.AntiForgeryToken() <table> <tr style="background-color: orange; padding: 25px;"> <td></td> <td> <input type="submit" value="Delete" /> @Html.ActionLink("Back to List", "Index") </td> </tr> </table> }
Details視圖:
@model Employee <h2>Employee Details</h2> <table> <tr> <td>@Html.DisplayNameFor(model => model.ID)</td> <td>@Html.DisplayFor(model => model.ID)</td> </tr> <tr> <td>@Html.DisplayNameFor(model => model.Name)</td> <td>@Html.DisplayFor(model => model.Name)</td> </tr> <tr> <td>@Html.DisplayNameFor(model => model.Email)</td> <td>@Html.DisplayFor(model => model.Email)</td> </tr> <tr style="background-color: orange; padding: 25px;"> <td></td> <td> @Html.ActionLink("Edit", "Edit", new { id = Model.ID }) | @Html.ActionLink("Back to List", "Index") </td> </tr> </table>
效果圖:
目錄
- 1.倉儲模式在MVC應用程式中的使用
- 2.泛型倉儲模式在MVC應用程式中的使用
- 3.MVC Code-First和倉儲模式的應用
- 4.待續....