1.倉儲模式在MVC應用程式中的使用

来源:http://www.cnblogs.com/caofangsheng/archive/2016/04/10/5373998.html
-Advertisement-
Play Games

目錄 1.倉儲模式在MVC應用程式中的使用 2.泛型倉儲模式在MVC應用程式中的使用 3.MVC Code-First和倉儲模式的應用 4.待續.... 附上源代碼:https://github.com/caofangsheng93/CaoDanDeGit 這篇文章中,我會解釋倉儲模式在MVC程式中 ...


目錄     

 

附上源代碼: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>  

效果圖:

 

目錄     

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 2016-04-07 張超《Linux內核分析》MOOC課程http://mooc.study.163.com/course/USTC-1000029000#/info 一、理解編譯鏈接的過程和ELF可執行文件格式 我給出了一個例子: 第一步:先編輯一個hello.c,如下 vi hello.c 1 ...
  • 在System.Net.Http中,提供了使用Http與遠程伺服器通訊的httpClient,但是裡面都是非同步方法,有時候我們並不需要使用非同步操作。這個時候可以使用如下的方式來進行同步調用。 不阻塞主線程的非同步操作,可以參考:HttpClient介紹。 ...
  • 一、引言 在前一篇博文已經介紹瞭如何使用SignalR來實現聊天室的功能,在這篇文章中,將實現如何使用SignalR來實現發送圖片的功能。 二、實現發送圖片的思路 我還是按照之前的方式來講述這篇文章,首先,讓我們來理清下實現發送圖片功能的思路。 圖片的顯示,除了直接指定圖片的路徑外(這種實現方式也稱 ...
  • 在上一篇我的第一個FluentNHibernate例子的基礎上,我們用上knockoutjs 1用nuget添加knockoutjs包 2用nuget添加json.net包 3..在Index.cshtml中添加 4.添加script在table後面 <script> function ViewMo ...
  • 2個集合合併,有相同的只取中其一個: source code: ...
  • 找到兩個集合中交集部分: source code: ...
  • 在兩個集合中,左邊集合減去右邊集合的元素: source code: ...
  • Modern UI WPF包括兩個內置主題(dark與light)。在1.0.3版本,您可以構建自定義的主題。Modern UI應用程式通常有在全局資源字典App.xaml中有如下定義: “/FirstFloor.ModernUI;component/Assets/ModernUI.xaml”字典包... ...
一周排行
    -Advertisement-
    Play Games
  • .Net8.0 Blazor Hybird 桌面端 (WPF/Winform) 實測可以完整運行在 win7sp1/win10/win11. 如果用其他工具打包,還可以運行在mac/linux下, 傳送門BlazorHybrid 發佈為無依賴包方式 安裝 WebView2Runtime 1.57 M ...
  • 目錄前言PostgreSql安裝測試額外Nuget安裝Person.cs模擬運行Navicate連postgresql解決方案Garnet為什麼要選擇Garnet而不是RedisRedis不再開源Windows版的Redis是由微軟維護的Windows Redis版本老舊,後續可能不再更新Garne ...
  • C#TMS系統代碼-聯表報表學習 領導被裁了之後很快就有人上任了,幾乎是無縫銜接,很難讓我不想到這早就決定好了。我的職責沒有任何變化。感受下來這個系統封裝程度很高,我只要會調用方法就行。這個系統交付之後不會有太多問題,更多應該是做小需求,有大的開發任務應該也是第二期的事,嗯?怎麼感覺我變成運維了?而 ...
  • 我在隨筆《EAV模型(實體-屬性-值)的設計和低代碼的處理方案(1)》中介紹了一些基本的EAV模型設計知識和基於Winform場景下低代碼(或者說無代碼)的一些實現思路,在本篇隨筆中,我們來分析一下這種針對通用業務,且只需定義就能構建業務模塊存儲和界面的解決方案,其中的數據查詢處理的操作。 ...
  • 對某個遠程伺服器啟用和設置NTP服務(Windows系統) 打開註冊表 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W32Time\TimeProviders\NtpServer 將 Enabled 的值設置為 1,這將啟用NTP伺服器功 ...
  • title: Django信號與擴展:深入理解與實踐 date: 2024/5/15 22:40:52 updated: 2024/5/15 22:40:52 categories: 後端開發 tags: Django 信號 松耦合 觀察者 擴展 安全 性能 第一部分:Django信號基礎 Djan ...
  • 使用xadmin2遇到的問題&解決 環境配置: 使用的模塊版本: 關聯的包 Django 3.2.15 mysqlclient 2.2.4 xadmin 2.0.1 django-crispy-forms >= 1.6.0 django-import-export >= 0.5.1 django-r ...
  • 今天我打算整點兒不一樣的內容,通過之前學習的TransformerMap和LazyMap鏈,想搞點不一樣的,所以我關註了另外一條鏈DefaultedMap鏈,主要調用鏈為: 調用鏈詳細描述: ObjectInputStream.readObject() DefaultedMap.readObject ...
  • 後端應用級開發者該如何擁抱 AI GC?就是在這樣的一個大的浪潮下,我們的傳統的應用級開發者。我們該如何選擇職業或者是如何去快速轉型,跟上這樣的一個行業的一個浪潮? 0 AI金字塔模型 越往上它的整個難度就是職業機會也好,或者說是整個的這個運作也好,它的難度會越大,然後越往下機會就會越多,所以這是一 ...
  • @Autowired是Spring框架提供的註解,@Resource是Java EE 5規範提供的註解。 @Autowired預設按照類型自動裝配,而@Resource預設按照名稱自動裝配。 @Autowired支持@Qualifier註解來指定裝配哪一個具有相同類型的bean,而@Resourc... ...