標籤:
上一講我們建立了一系列的解決方案,我們通過一個例子來看看層與層之間的關係。
我們把Controllers分離出來了BLL層和DAL層
BLL專註於業務上的處理
DAL專註於資料訪問層的處理
而Controller跟清楚的與View互動
我們上一講已經在EF添加了一個實體SysSample
下面我們建立IDAL,DAL,IBLL,BLL的代碼吧
using App.Models;using System.Linq;namespace App.IDAL{ public interface ISysSampleRepository { /// <summary> /// 擷取列表 /// </summary> /// <param name="db">資料庫上下文</param> /// <returns>資料列表</returns> IQueryable<SysSample> GetList(DBContainer db); /// <summary> /// 建立一個實體 /// </summary> /// <param name="entity">實體</param> int Create(SysSample entity); /// <summary> /// 刪除一個實體 /// </summary> /// <param name="entity">主鍵ID</param> int Delete(string id); /// <summary> /// 修改一個實體 /// </summary> /// <param name="entity">實體</param> int Edit(SysSample entity); /// <summary> /// 獲得一個實體 /// </summary> /// <param name="id">id</param> /// <returns>實體</returns> SysSample GetById(string id); /// <summary> /// 判斷一個實體是否存在 /// </summary> bool IsExist(string id); }}ISysSampleRepository.cs
using System;using System.Linq;using App.IDAL;using App.Models;using System.Data;namespace App.DAL{ public class SysSampleRepository : ISysSampleRepository, IDisposable { /// <summary> /// 擷取列表 /// </summary> /// <param name="db">資料庫上下文</param> /// <returns>資料列表</returns> public IQueryable<SysSample> GetList(DBContainer db) { IQueryable<SysSample> list = db.SysSample.AsQueryable(); return list; } /// <summary> /// 建立一個實體 /// </summary> /// <param name="db">資料庫上下文</param> /// <param name="entity">實體</param> public int Create(SysSample entity) { using (DBContainer db = new DBContainer()) { db.SysSample.AddObject(entity); return db.SaveChanges(); } } /// <summary> /// 刪除一個實體 /// </summary> /// <param name="db">資料庫上下文</param> /// <param name="entity">主鍵ID</param> public int Delete(string id) { using (DBContainer db = new DBContainer()) { SysSample entity = db.SysSample.SingleOrDefault(a => a.Id == id); if (entity != null) { db.SysSample.DeleteObject(entity); } return db.SaveChanges(); } } /// <summary> /// 修改一個實體 /// </summary> /// <param name="db">資料庫上下文</param> /// <param name="entity">實體</param> public int Edit(SysSample entity) { using (DBContainer db = new DBContainer()) { db.SysSample.Attach(entity); db.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified); return db.SaveChanges(); } } /// <summary> /// 獲得一個實體 /// </summary> /// <param name="id">id</param> /// <returns>實體</returns> public SysSample GetById(string id) { using (DBContainer db = new DBContainer()) { return db.SysSample.SingleOrDefault(a => a.Id == id); } } /// <summary> /// 判斷一個實體是否存在 /// </summary> /// <param name="id">id</param> /// <returns>是否存在 true or false</returns> public bool IsExist(string id) { using (DBContainer db = new DBContainer()) { SysSample entity = GetById(id); if (entity != null) return true; return false; } } public void Dispose() { } }}SysSampleRepository.cs
//------------------------------------------------------------------------------// <auto-generated>// 此代碼由T4模板自動產生// 產生時間 2013-03-12 11:19:12 by App// 對此檔案的更改可能會導致不正確的行為,並且如果// 重建代碼,這些更改將會丟失。// </auto-generated>//------------------------------------------------------------------------------using System.Collections.Generic;using App.Models;namespace App.IBLL{ public interface ISysSampleBLL { /// <summary> /// 擷取列表 /// </summary> /// <param name="pager">JQgrid分頁</param> /// <param name="queryStr">搜尋條件</param> /// <returns>列表</returns> List<SysSample> GetList(string queryStr); /// <summary> /// 建立一個實體 /// </summary> /// <param name="errors">持久的錯誤資訊</param> /// <param name="model">模型</param> /// <returns>是否成功</returns> bool Create(SysSample model); /// <summary> /// 刪除一個實體 /// </summary> /// <param name="errors">持久的錯誤資訊</param> /// <param name="id">id</param> /// <returns>是否成功</returns> bool Delete(string id); /// <summary> /// 修改一個實體 /// </summary> /// <param name="errors">持久的錯誤資訊</param> /// <param name="model">模型</param> /// <returns>是否成功</returns> bool Edit(SysSample model); /// <summary> /// 根據ID獲得一個Model實體 /// </summary> /// <param name="id">id</param> /// <returns>Model實體</returns> SysSample GetById(string id); /// <summary> /// 判斷是否存在實體 /// </summary> /// <param name="id">主鍵ID</param> /// <returns>是否存在</returns> bool IsExist(string id); }}ISysSampleBLL
using System;using System.Collections.Generic;using System.Linq;using App.Models;using App.Common;using App.IBLL;using App.IDAL;using App.DAL;namespace App.BLL{ public class SysSampleBLL :ISysSampleBLL { DBContainer db = new DBContainer(); ISysSampleRepository Rep = new SysSampleRepository(); /// <summary> /// 擷取列表 /// </summary> /// <param name="pager">JQgrid分頁</param> /// <param name="queryStr">搜尋條件</param> /// <returns>列表</returns> public List<SysSample> GetList(string queryStr) { IQueryable<SysSample> queryData =Rep.GetList(db); return queryData.ToList(); } /// <summary> /// 建立一個實體 /// </summary> /// <param name="errors">持久的錯誤資訊</param> /// <param name="model">模型</param> /// <returns>是否成功</returns> public bool Create(SysSample entity) { try { if (Rep.Create(entity) == 1) { return true; } else { return false; } } catch (Exception ex) { //ExceptionHander.WriteException(ex); return false; } } /// <summary> /// 刪除一個實體 /// </summary> /// <param name="errors">持久的錯誤資訊</param> /// <param name="id">id</param> /// <returns>是否成功</returns> public bool Delete(string id) { try { if (Rep.Delete(id) == 1) { return true; } else { return false; } } catch (Exception ex) { //ExceptionHander.WriteException(ex); return false; } } /// <summary> /// 修改一個實體 /// </summary> /// <param name="errors">持久的錯誤資訊</param> /// <param name="model">模型</param> /// <returns>是否成功</returns> public bool Edit(SysSample entity) { try { if (Rep.Edit(entity) == 1) { return true; } else { return false; } } catch (Exception ex) { //ExceptionHander.WriteException(ex); return false; } } /// <summary> /// 判斷是否存在實體 /// </summary> /// <param name="id">主鍵ID</param> /// <returns>是否存在</returns> public bool IsExists(string id) { if (db.SysSample.SingleOrDefault(a => a.Id == id) != null) { return true; } return false; } /// <summary> /// 根據ID獲得一個實體 /// </summary> /// <param name="id">id</param> /// <returns>實體</returns> public SysSample GetById(string id) { if (IsExist(id)) { SysSample entity = Rep.GetById(id); return entity; } else { return null; } } /// <summary> /// 判斷一個實體是否存在 /// </summary> /// <param name="id">id</param> /// <returns>是否存在 true or false</returns> public bool IsExist(string id) { return Rep.IsExist(id); } }}SysSampleBLL
介面是用來整合的,所以BLL:IBLL DAL:IDAL
上面的類注釋都很明白明了了。(只是代碼很糟糕)
我們建立一個空控制器 SysSample,並添加index視圖
@model IEnumerable<App.Models.SysSample>@{ Layout = null;}<!DOCTYPE html><html><head> <meta name="viewport" content="width=device-width" /> <title>Index</title></head><body> <p> @Html.ActionLink("Create New", "Create") </p> <table> <tr> <th> @Html.DisplayNameFor(model => model.Name) </th> <th> @Html.DisplayNameFor(model => model.Age) </th> <th> @Html.DisplayNameFor(model => model.Bir) </th> <th> @Html.DisplayNameFor(model => model.Photo) </th> <th> @Html.DisplayNameFor(model => model.Note) </th> <th> @Html.DisplayNameFor(model => model.CreateTime) </th> <th></th> </tr> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.Name) </td> <td> @Html.DisplayFor(modelItem => item.Age) </td> <td> @Html.DisplayFor(modelItem => item.Bir) </td> <td> @Html.DisplayFor(modelItem => item.Photo) </td> <td> @Html.DisplayFor(modelItem => item.Note) </td> <td> @Html.DisplayFor(modelItem => item.CreateTime) </td> <td> @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></body></html>Index.cshtml
開啟Home index的第48行修改為<iframe scrolling="auto" frameborder="0" src="/SysSample" style="width: 100%; height: 100%;"></iframe>
我們將在easyui架構預覽
運行之後你可能會報錯資料庫沒得串連,因為我們把EF放到了App.Models下,在App.Admin的web.config需要修改connectionStrings
為App.Models下的App.Config的connectionStrings包含節點
編譯器錯誤訊息: CS0012: 類型“System.Data.Objects.DataClasses.EntityObject”在未被引用的程式集中定義。
必須添加對程式集 “System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089” 的引用。
開啟web.config 尋找compilation debug="true" targetFramework="4.5"
添加節點
<assemblies>
<add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
</assemblies>
這裡給出web.config
<?xml version="1.0" encoding="utf-8"?><!-- 有關如何配置 ASP.NET 應用程式的詳細資料,請訪問 http://go.microsoft.com/fwlink/?LinkId=169433 --><configuration> <configSections> <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --> <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /> </configSections> <connectionStrings> <add name="DBContainer" connectionString="metadata=res://*/DB.csdl|res://*/DB.ssdl|res://*/DB.msl;provider=System.Data.SqlClient;provider connection string="data source=.;initial catalog=DB;user id=sa;[email protected]#;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" /> </connectionStrings> <appSettings> <add key="webpages:Version" value="2.0.0.0" /> <add key="webpages:Enabled" value="false" /> <add key="PreserveLoginUrl" value="true" /> <add key="ClientValidationEnabled" value="true" /> <add key="UnobtrusiveJavaScriptEnabled" value="true" /> </appSettings> <system.web> <compilation debug="true" targetFramework="4.5" > <assemblies> <add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/> </assemblies> </compilation> <httpRuntime targetFramework="4.5" /> <authentication mode="Forms"> <forms loginUrl="~/Account/Login" timeout="2880" /> </authentication> <pages> <namespaces> <add namespace="System.Web.Helpers" /> <add namespace="System.Web.Mvc" /> <add namespace="System.Web.Mvc.Ajax" /> <add namespace="System.Web.Mvc.Html" /> <add namespace="System.Web.Optimization" /> <add namespace="System.Web.Routing" /> <add namespace="System.Web.WebPages" /> </namespaces> </pages> </system.web> <system.webServer> <validation validateIntegratedModeConfiguration="false" /> <handlers> <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" /> <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" /> <remove name="ExtensionlessUrlHandler-Integrated-4.0" /> <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" /> <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" /> <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" /> </handlers> </system.webServer> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="DotNetOpenAuth.Core" publicKeyToken="2780ccd10d57b246" /> <bindingRedirect oldVersion="1.0.0.0-4.0.0.0" newVersion="4.1.0.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="DotNetOpenAuth.AspNet" publicKeyToken="2780ccd10d57b246" /> <bindingRedirect oldVersion="1.0.0.0-4.0.0.0" newVersion="4.1.0.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="1.0.0.0-4.0.0.0" newVersion="4.0.0.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="1.0.0.0-1.3.0.0" newVersion="1.3.0.0" /> </dependentAssembly> </assemblyBinding> </runtime> <entityFramework> <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" /> </entityFramework></configuration>web.config
修改SysSampleController ,修改Index()的方法,代碼如下:
public class SysSampleController : Controller { // // GET: /SysSample/ public ActionResult Index() { SysSampleBLL bll = new SysSampleBLL(); List<SysSample> list = bll.GetList(""); return View(list); } }
我們往資料庫插入幾條記錄這時你應該看到效果了
BLL DAL的增刪改都做好了,大家有興趣就補充一下下吧,都說破了就不好啦。
構建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的後台管理系統(5)-EF增刪改查by糟糕的代碼