系列概述:全系列會詳細介紹抽象工廠三層的搭建,以及EF高級應用和 ASP.NET MVC3.0簡單應用,應用到的技術有Ef、Lambda、Linq、Interface、T4等。
由於網上對涉及到的技術概念介紹很多,因此本項目中不再對基本概念加以敘述。
系列二概述:該系列詳細介紹了如何抽象出公用方法(CRUD),以及T4模版的應用。
一、創建Cnblogs.Rdst.IDAO程序集
1.1 先在解決方案中創建一個Interface 文件夾,用於存放抽象出的接口
1.2 在Interface文件夾中添加名為Cnblogs.Rdst.IDAO的程序集
1.3 添加引用系列一中創建的Domain程序集和System.Data.Entity程序集
二、抽象數據訪問層的基接口
2.1 在剛創建的Cnblogs.Rdst.IDAO程序集中創建IBaseDao接口
2.2 在IBaseDao中定義常用的CRUD方法
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 namespace Cnblogs.Rdst.IDAO 7 { 8 public interface IBaseDao<T> 9 where T:class, 10 new ()//約束T類型必須可以實例化 11 { 12 //根據條件獲取實體對象集合 13 IQueryable<T> LoadEntites(Func<T,bool> whereLambda ); 14 15 //根據條件獲取實體對象集合分頁 16 IQueryable<T> LoadEntites(Func<T,bool> whereLambda, int pageIndex, int pageSize,out int totalCount); 17 18 //增加 19 T AddEntity(T entity); 20 21 //更新 22 T UpdateEntity(T entity); 23 24 //刪除 25 bool DelEntity(T entity); 26 27 //根據條件刪除 28 bool DelEntityByWhere(Func<T, bool> whereLambda); 29 } 30 }
此時基接口中的CRUD方法就定義完成。接下來我們需要使用T4模版生成所有的實體類接口並實現IBaseDao接口。
三、生成所有的實體類接口
3.1 添加名為IDaoExt 的T4文本模版
3.2 在模版中貼入以下代碼,其中注釋的地方需要根據各自的項目進行更改
<#@ 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 = @"..\\Cnblogs.Rdst.Domain\\Model.edmx";//指定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; using Cnblogs.Rdst.Domain;//引用Domain的命名空間 namespace Cnblogs.Rdst.IDAO //實體類接口所在的命名空間 { <# foreach (EntityType entity in ItemCollection.GetItems<EntityType>().OrderBy(e => e.Name)) //便利edmx模型中映射的實體對象 {#> public interface I<#=entity.Name#>Dao:IBaseDao<<#=entity.Name#>> //生成實體對象接口 { } <#};#> }
3.3 T4模版編輯完成后,Ctrl+s保存,提示是否運行,點擊確認。此時就自動幫我們生成了所有的實體類接口,並實現了IBaseDao接口,相應的也具有了CRUD方法定義。
菜鳥級三層框架(EF+MVC)項目實戰之 系列二 對數據訪問層的抽象中 會介紹實現類中是如何實現基接口中定義的方法







