23、ASP.NET MVC入門到精通——業務層和資料層父類及介面-T4模板
在上一篇中,我們已經把專案的基本框架搭起來了,這一篇我們就來實現業務層和資料層的父介面及父類。
1、我們先來定義一個業務層父介面IBaseBLL.cs
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; namespace IBLL { /// <summary> /// 業務父 介面 /// </summary>View Code/// <typeparam name="T"></typeparam> public interface IBaseBLL<T> where T:class,new() { //定義 增刪改查 方法 #region 1.0 新增 實體 +int Add(T model) /// <summary> /// 新增 實體 /// </summary> /// <param name="model"></param> ///<returns></returns> int Add(T model); #endregion #region 2.0 根據 id 刪除 +int Del(T model) /// <summary> /// 根據 id 刪除 /// </summary> /// <param name="model">包含要刪除id的物件</param> /// <returns></returns> intDel(T model); #endregion #region 3.0 根據條件刪除 +int DelBy(Expression<Func<T, bool>> delWhere) /// <summary> /// 3.0 根據條件刪除 /// </summary> /// <param name="delWhere"></param> /// <returns></returns> int DelBy(Expression<Func<T, bool>> delWhere); #endregion #region 4.0 修改 +int Modify(T model, params string[] proNames) /// <summary> /// 4.0 修改,如: /// T u = new T() { uId = 1, uLoginName = "asdfasdf" }; /// this.Modify(u, "uLoginName"); /// </summary> /// <param name="model">要修改的實體物件</param> /// <param name="proNames">要修改的 屬性 名稱</param> /// <returns></returns> int Modify(T model, params string[] proNames); #endregion #region 4.0 批量修改 +int Modify(T model, Expression<Func<T, bool>> whereLambda, params string[] modifiedProNames) /// <summary> /// 4.0 批量修改 /// </summary> /// <param name="model">要修改的實體物件</param> /// <param name="whereLambda">查詢條件</param> /// <param name="proNames">要修改的 屬性 名稱</param> /// <returns></returns> int ModifyBy(T model, Expression<Func<T, bool>> whereLambda, params string[] modifiedProNames); #endregion #region 5.0 根據條件查詢 +List<T> GetListBy(Expression<Func<T,bool>> whereLambda) /// <summary> /// 5.0 根據條件查詢 +List<T> GetListBy(Expression<Func<T,bool>> whereLambda) /// </summary> /// <param name="whereLambda"></param> /// <returns></returns> List<T> GetListBy(Expression<Func<T, bool>> whereLambda); #endregion #region 5.1 根據條件 排序 和查詢 + List<T> GetListBy<TKey> /// <summary> /// 5.1 根據條件 排序 和查詢 /// </summary> /// <typeparam name="TKey">排序欄位型別</typeparam> /// <param name="whereLambda">查詢條件 lambda表示式</param> /// <param name="orderLambda">排序條件 lambda表示式</param> /// <returns></returns> List<T> GetListBy<TKey>(Expression<Func<T, bool>> whereLambda, Expression<Func<T, TKey>> orderLambda); #endregion #region 6.0 分頁查詢 + List<T> GetPagedList<TKey> /// <summary> /// 6.0 分頁查詢 + List<T> GetPagedList<TKey> /// </summary> /// <param name="pageIndex">頁碼</param> /// <param name="pageSize">頁容量</param> /// <param name="whereLambda">條件 lambda表示式</param> /// <param name="orderBy">排序 lambda表示式</param> /// <returns></returns> List<T> GetPagedList<TKey>(int pageIndex, int pageSize, Expression<Func<T, bool>> whereLambda, Expression<Func<T, TKey>> orderBy); #endregion } }
2、定義一個數據層父介面IBaseDAL.cs
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; namespace IDAL { /// <summary> /// 資料層父介面 /// </summary> public interface IBaseDAL<T> where T:class ,new() { //定義增刪改查方法 #region 1.0 新增 實體 +int Add(T model) /// <summary> /// 新增 實體 /// </summary> /// <param name="model"></param> /// <returns></returns> int Add(T model); #endregion #region 2.0 根據 id 刪除 +int Del(T model) /// <summary> /// 根據 id 刪除 /// </summary> /// <param name="model">包含要刪除id的物件</param> /// <returns></returns> int Del(T model); #endregion #region 3.0 根據條件刪除 +int DelBy(Expression<Func<T, bool>> delWhere) /// <summary> /// 3.0 根據條件刪除 /// </summary> /// <param name="delWhere"></param> /// <returns></returns> int DelBy(Expression<Func<T, bool>> delWhere); #endregion #region 4.0 修改 +int Modify(T model, params string[] proNames) /// <summary> /// 4.0 修改,如: /// T u = new T() { uId = 1, uLoginName = "asdfasdf" }; /// this.Modify(u, "uLoginName"); /// </summary> /// <param name="model">要修改的實體物件</param> /// <param name="proNames">要修改的 屬性 名稱</param> /// <returns></returns> int Modify(T model, params string[] proNames); #endregion #region 4.0 批量修改 +int Modify(T model, Expression<Func<T, bool>> whereLambda, params string[] modifiedProNames) /// <summary> /// 4.0 批量修改 /// </summary> /// <param name="model">要修改的實體物件</param> /// <param name="whereLambda">查詢條件</param> /// <param name="proNames">要修改的 屬性 名稱</param> /// <returns></returns> int ModifyBy(T model, Expression<Func<T, bool>> whereLambda, params string[] modifiedProNames); #endregion #region 5.0 根據條件查詢 +List<T> GetListBy(Expression<Func<T,bool>> whereLambda) /// <summary> /// 5.0 根據條件查詢 +List<T> GetListBy(Expression<Func<T,bool>> whereLambda) /// </summary> /// <param name="whereLambda"></param> /// <returns></returns> List<T> GetListBy(Expression<Func<T, bool>> whereLambda); #endregion #region 5.1 根據條件 排序 和查詢 + List<T> GetListBy<TKey> /// <summary> /// 5.1 根據條件 排序 和查詢 /// </summary> /// <typeparam name="TKey">排序欄位型別</typeparam> /// <param name="whereLambda">查詢條件 lambda表示式</param> /// <param name="orderLambda">排序條件 lambda表示式</param> /// <returns></returns> List<T> GetListBy<TKey>(Expression<Func<T, bool>> whereLambda, Expression<Func<T, TKey>> orderLambda); #endregion #region 6.0 分頁查詢 + List<T> GetPagedList<TKey> /// <summary> /// 6.0 分頁查詢 + List<T> GetPagedList<TKey> /// </summary> /// <param name="pageIndex">頁碼</param> /// <param name="pageSize">頁容量</param> /// <param name="whereLambda">條件 lambda表示式</param> /// <param name="orderBy">排序 lambda表示式</param> /// <returns></returns> List<T> GetPagedList<TKey>(int pageIndex, int pageSize, Expression<Func<T, bool>> whereLambda, Expression<Func<T, TKey>> orderBy); #endregion } }View Code
3、我們資料庫中有許多的表,通常每一張表都對應一個業務實體,如果我們每一個業務實體類都自己去手寫的話,太浪費時間了,我們可以使用T4模板,簡化這些枯燥的操作,提高我們的開發效率。
新建一個文字模板
然後把以下程式碼複製上去,
<#@ template language="C#" debug="false" hostspecific="true"#> <#@ include file="EF.Utility.CS.ttinclude"#><#@ output extension=".cs"#> <# CodeGenerationTools code = new CodeGenerationTools(this); MetadataLoader loader = new MetadataLoader(this); CodeRegion region = new CodeRegion(this, 1); MetadataTools ef = new MetadataTools(this); string inputFile = @"..\MODEL\OA.edmx"; EdmItemCollection ItemCollection = loader.CreateEdmItemCollection(inputFile); string namespaceName = code.VsNamespaceSuggestion(); EntityFrameworkTemplateFileManager fileManager = EntityFrameworkTemplateFileManager.Create(this); #> using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace IBLL { <# // Emit Entity Types foreach (EntityType entity in ItemCollection.GetItems<EntityType>().OrderBy(e => e.Name)) { //fileManager.StartNewFile(entity.Name + "RepositoryExt.cs"); //BeginNamespace(namespaceName, code); #> public partial interface I<#=entity.Name#>BLL : IBaseBLL<Model.<#=entity.Name#>> { } <#}#> }View Code
當然,你也可以使用NuGet安裝tangibleT4EditorPlusModellingToolsVS2012,安裝完成後,按照如下的方式新增T4模板
按Ctrl+S自動生成程式碼,自動生成的IBLL.cs如下:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace IBLL { public partial interface IBill_LeaveBLL : IBaseBLL<Model.Bill_Leave> { } public partial interface IoldWF_AutoTransactNodeBLL : IBaseBLL<Model.oldWF_AutoTransactNode> { } public partial interface IoldWF_BillFlowNodeBLL : IBaseBLL<Model.oldWF_BillFlowNode> { } public partial interface IoldWF_BillFlowNodeRemarkBLL : IBaseBLL<Model.oldWF_BillFlowNodeRemark> { } public partial interface IoldWF_BillStateBLL : IBaseBLL<Model.oldWF_BillState> { } public partial interface IoldWF_NodeBLL : IBaseBLL<Model.oldWF_Node> { } public partial interface IoldWF_NodeStateBLL : IBaseBLL<Model.oldWF_NodeState> { } public partial interface IoldWF_WorkFlowBLL : IBaseBLL<Model.oldWF_WorkFlow> { } public partial interface IoldWF_WorkFlowNodeBLL : IBaseBLL<Model.oldWF_WorkFlowNode> { } public partial interface IOu_DepartmentBLL : IBaseBLL<Model.Ou_Department> { } public partial interface IOu_PermissionBLL : IBaseBLL<Model.Ou_Permission> { } public partial interface IOu_RoleBLL : IBaseBLL<Model.Ou_Role> { } public partial interface IOu_RolePermissionBLL : IBaseBLL<Model.Ou_RolePermission> { } public partial interface IOu_UserInfoBLL : IBaseBLL<Model.Ou_UserInfo> { } public partial interface IOu_UserRoleBLL : IBaseBLL<Model.Ou_UserRole> { } public partial interface IOu_UserVipPermissionBLL : IBaseBLL<Model.Ou_UserVipPermission> { } public partial interface IW_WorkFlowBLL : IBaseBLL<Model.W_WorkFlow> { } public partial interface IW_WorkFlowBranchBLL : IBaseBLL<Model.W_WorkFlowBranch> { } public partial interface IW_WorkFlowNodeBLL : IBaseBLL<Model.W_WorkFlowNode> { } public partial interface IW_WrokFlowRoleBLL : IBaseBLL<Model.W_WrokFlowRole> { } public partial interface IWR_WorkFlowApplyBLL : IBaseBLL<Model.WR_WorkFlowApply> { } public partial interface IWR_WrokFlowApplyDetailsBLL : IBaseBLL<Model.WR_WrokFlowApplyDetails> { } }View Code
4、把IBLL.tt拷貝到IDAL專案下,然後修改名稱空間為IDAL,修改介面宣告模板
namespace IDAL public partial interface I<#=entity.Name#>DAL : IBaseDAL<Model.<#=entity.Name#>>
按Ctrl+S自動生成程式碼,自動生成的IDAL.cs如下:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace IDAL { public partial interface IBill_LeaveDAL : IBaseDAL<Model.Bill_Leave> { } public partial interface IoldWF_AutoTransactNodeDAL : IBaseDAL<Model.oldWF_AutoTransactNode> { } public partial interface IoldWF_BillFlowNodeDAL : IBaseDAL<Model.oldWF_BillFlowNode> { } public partial interface IoldWF_BillFlowNodeRemarkDAL : IBaseDAL<Model.oldWF_BillFlowNodeRemark> { } public partial interface IoldWF_BillStateDAL : IBaseDAL<Model.oldWF_BillState> { } public partial interface IoldWF_NodeDAL : IBaseDAL<Model.oldWF_Node> { } public partial interface IoldWF_NodeStateDAL : IBaseDAL<Model.oldWF_NodeState> { } public partial interface IoldWF_WorkFlowDAL : IBaseDAL<Model.oldWF_WorkFlow> { } public partial interface IoldWF_WorkFlowNodeDAL : IBaseDAL<Model.oldWF_WorkFlowNode> { } public partial interface IOu_DepartmentDAL : IBaseDAL<Model.Ou_Department> { } public partial interface IOu_PermissionDAL : IBaseDAL<Model.Ou_Permission> { } public partial interface IOu_RoleDAL : IBaseDAL<Model.Ou_Role> { } public partial interface IOu_RolePermissionDAL : IBaseDAL<Model.Ou_RolePermission> { } public partial interface IOu_UserInfoDAL : IBaseDAL<Model.Ou_UserInfo> { } public partial interface IOu_UserRoleDAL : IBaseDAL<Model.Ou_UserRole> { } public partial interface IOu_UserVipPermissionDAL : IBaseDAL<Model.Ou_UserVipPermission> { } public partial interface IW_WorkFlowDAL : IBaseDAL<Model.W_WorkFlow> { } public partial interface IW_WorkFlowBranchDAL : IBaseDAL<Model.W_WorkFlowBranch> { } public partial interface IW_WorkFlowNodeDAL : IBaseDAL<Model.W_WorkFlowNode> { } public partial interface IW_WrokFlowRoleDAL : IBaseDAL<Model.W_WrokFlowRole> { } public partial interface IWR_WorkFlowApplyDAL : IBaseDAL<Model.WR_WorkFlowApply> { } public partial interface IWR_WrokFlowApplyDetailsDAL : IBaseDAL<Model.WR_WrokFlowApplyDetails> { } }View Code
注意,我這裡生成的所有介面都是partial型別的,這樣我以後可以很方便的進行擴充套件
關於T4模板的使用不在本篇所講的範疇,有興趣的朋友,可以查詢相關資料學習,我這裡只做簡要說明。
<#@ include file="EF.Utility.CS.ttinclude"#>:引入微軟的生成框架
<#@ output extension=".cs"#>:指定生成的檔案型別為.cs檔案
string inputFile = @"..\MODEL\OA.edmx":這裡使用相對路徑指向我們新建的ADO.NET實體資料模型檔案。
5、新增資料層的父類BaseDAL.cs
前面資料層介面和業務層介面都已經新增好了,那麼現在來新增資料層類和業務層類
在DAL專案中新增EntityFramework.dll和System.Data.Entity.dll的引用
using System; using System.Collections.Generic; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Text; using Model; namespace DAL { /// <summary> /// 資料層 父類 /// </summary> /// <typeparam name="T"></typeparam> public class BaseDAL<T> : IDAL.IBaseDAL<T> where T : class,new() { /// <summary> /// EF上下文物件 /// </summary> DbContext db = new OAEntities(); //new DBContextFactory().GetDbContext();// #region 1.0 新增 實體 +int Add(T model) /// <summary> /// 新增 實體 /// </summary> /// <param name="model"></param> /// <returns></returns> public int Add(T model) { db.Set<T>().Add(model); return db.SaveChanges();//儲存成功後,會將自增的id設定給 model的 主鍵屬性,並返回受影響行數 } #endregion #region 2.0 根據 id 刪除 +int Del(T model) /// <summary> /// 根據 id 刪除 /// </summary> /// <param name="model">包含要刪除id的物件</param> /// <returns></returns> public int Del(T model) { db.Set<T>().Attach(model); db.Set<T>().Remove(model); return db.SaveChanges(); } #endregion #region 3.0 根據條件刪除 +int DelBy(Expression<Func<T, bool>> delWhere) /// <summary> /// 3.0 根據條件刪除 /// </summary> /// <param name="delWhere"></param> /// <returns></returns> public int DelBy(Expression<Func<T, bool>> delWhere) { //3.1查詢要刪除的資料 List<T> listDeleting = db.Set<T>().Where(delWhere).ToList(); //3.2將要刪除的資料 用刪除方法新增到 EF 容器中 listDeleting.ForEach(u => { db.Set<T>().Attach(u);//先附加到 EF容器 db.Set<T>().Remove(u);//標識為 刪除 狀態 }); //3.3一次性 生成sql語句到資料庫執行刪除 return db.SaveChanges(); } #endregion #region 4.0 修改 +int Modify(T model, params string[] proNames) /// <summary> /// 4.0 修改,如: /// T u = new T() { uId = 1, uLoginName = "asdfasdf" }; /// this.Modify(u, "uLoginName"); /// </summary> /// <param name="model">要修改的實體物件</param> /// <param name="proNames">要修改的 屬性 名稱</param> /// <returns></returns> public int Modify(T model, params string[] proNames) { //4.1將 物件 新增到 EF中 DbEntityEntry entry = db.Entry<T>(model); //4.2先設定 物件的包裝 狀態為 Unchanged entry.State = System.Data.EntityState.Unchanged; //4.3迴圈 被修改的屬性名 陣列 foreach (string proName in proNames) { //4.4將每個 被修改的屬性的狀態 設定為已修改狀態;後面生成update語句時,就只為已修改的屬性 更新 entry.Property(proName).IsModified = true; } //4.4一次性 生成sql語句到資料庫執行 return db.SaveChanges(); } #endregion #region 4.0 批量修改 +int Modify(T model, Expression<Func<T, bool>> whereLambda, params string[] modifiedProNames) /// <summary> /// 4.0 批量修改 /// </summary> /// <param name="model">要修改的實體物件</param> /// <param name="whereLambda">查詢條件</param> /// <param name="proNames">要修改的 屬性 名稱</param> /// <returns></returns> public int ModifyBy(T model, Expression<Func<T, bool>> whereLambda, params string[] modifiedProNames) { //4.1查詢要修改的資料 List<T> listModifing = db.Set<T>().Where(whereLambda).ToList(); //獲取 實體類 型別物件 Type t = typeof(T); // model.GetType(); //獲取 實體類 所有的 公有屬性 List<PropertyInfo> proInfos = t.GetProperties(BindingFlags.Instance | BindingFlags.Public).ToList(); //建立 實體屬性 字典集合 Dictionary<string, PropertyInfo> dictPros = new Dictionary<string, PropertyInfo>(); //將 實體屬性 中要修改的屬性名 新增到 字典集合中 鍵:屬性名 值:屬性物件 proInfos.ForEach(p => { if (modifiedProNames.Contains(p.Name)) { dictPros.Add(p.Name, p); } }); //4.3迴圈 要修改的屬性名 foreach (string proName in modifiedProNames) { //判斷 要修改的屬性名是否在 實體類的屬性集合中存在 if (dictPros.ContainsKey(proName)) { //如果存在,則取出要修改的 屬性物件 PropertyInfo proInfo = dictPros[proName]; //取出 要修改的值 object newValue = proInfo.GetValue(model, null); //object newValue = model.uName; //4.4批量設定 要修改 物件的 屬性 foreach (T usrO in listModifing) { //為 要修改的物件 的 要修改的屬性 設定新的值 proInfo.SetValue(usrO, newValue, null); //usrO.uName = newValue; } } } //4.4一次性 生成sql語句到資料庫執行 return db.SaveChanges(); } #endregion #region 5.0 根據條件查詢 +List<T> GetListBy(Expression<Func<T,bool>> whereLambda) /// <summary> /// 5.0 根據條件查詢 +List<T> GetListBy(Expression<Func<T,bool>> whereLambda) /// </summary> /// <param name="whereLambda"></param> /// <returns></returns> public List<T> GetListBy(Expression<Func<T, bool>> whereLambda) { return db.Set<T>().Where(whereLambda).ToList(); } #endregion #region 5.1 根據條件 排序 和查詢 + List<T> GetListBy<TKey> /// <summary> /// 5.1 根據條件 排序 和查詢 /// </summary> /// <typeparam name="TKey">排序欄位型別</typeparam> /// <param name="whereLambda">查詢條件 lambda表示式</param> /// <param name="orderLambda">排序條件 lambda表示式</param> /// <returns></returns> public List<T> GetListBy<TKey>