菜鳥級三層框架項目實戰(zhàn):對數(shù)據(jù)訪問層的抽象上
系列二概述:該系列詳細介紹了如何抽象出公用方法(CRUD),以及T4模版的應(yīng)用。
一、創(chuàng)建Cnblogs.Rdst.IDAO程序集
系列概述:全系列會詳細介紹抽象工廠三層的搭建,以及EF高級應(yīng)用和 ASP.NET MVC3.0簡單應(yīng)用,應(yīng)用到的技術(shù)有Ef、Lambda、Linq、Interface、T4等。
由于網(wǎng)上對涉及到的技術(shù)概念介紹很多,因此本項目中不再對基本概念加以敘述。
1.1 先在解決方案中創(chuàng)建一個Interface 文件夾,用于存放抽象出的接口
1.2 在Interface文件夾中添加名為Cnblogs.Rdst.IDAO的程序集
1.3 添加引用系列一中創(chuàng)建的Domain程序集和System.Data.Entity程序集
二、抽象數(shù)據(jù)訪問層的基接口
2.1 在剛創(chuàng)建的Cnblogs.Rdst.IDAO程序集中創(chuàng)建IBaseDao接口
2.2 在IBaseDao中定義常用的CRUD方法
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace Cnblogs.Rdst.IDAO
- {
- public interface IBaseDao<T>
- where T:class,
- new ()//約束T類型必須可以實例化
- {
- //根據(jù)條件獲取實體對象集合
- IQueryable<T> LoadEntites(Func<T,bool> whereLambda );
- //根據(jù)條件獲取實體對象集合分頁
- IQueryable<T> LoadEntites(Func<T,bool> whereLambda, int pageIndex, int pageSize,out int totalCount);
- //增加
- T AddEntity(T entity);
- //更新
- T UpdateEntity(T entity);
- //刪除
- bool DelEntity(T entity);
- //根據(jù)條件刪除
- bool DelEntityByWhere(Func<T, bool> whereLambda);
- }
- }
此時基接口中的CRUD方法就定義完成。接下來我們需要使用T4模版生成所有的實體類接口并實現(xiàn)IBaseDao接口。
三、生成所有的實體類接口
3.1 添加名為IDaoExt 的T4文本模版
3.2 在模版中貼入以下代碼,其中注釋的地方需要根據(jù)各自的項目進行更改
- <#@ 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保存,提示是否運行,點擊確認。此時就自動幫我們生成了所有的實體類接口,并實現(xiàn)了IBaseDao接口,相應(yīng)的也具有了CRUD方法定義。
原文鏈接:http://www.cnblogs.com/rdst/archive/2012/08/12/2634159.html