菜鳥級(jí)三層框架項(xiàng)目實(shí)戰(zhàn):對(duì)數(shù)據(jù)訪問層的抽象上
系列二概述:該系列詳細(xì)介紹了如何抽象出公用方法(CRUD),以及T4模版的應(yīng)用。
一、創(chuàng)建Cnblogs.Rdst.IDAO程序集
系列概述:全系列會(huì)詳細(xì)介紹抽象工廠三層的搭建,以及EF高級(jí)應(yīng)用和 ASP.NET MVC3.0簡單應(yīng)用,應(yīng)用到的技術(shù)有Ef、Lambda、Linq、Interface、T4等。
由于網(wǎng)上對(duì)涉及到的技術(shù)概念介紹很多,因此本項(xiàng)目中不再對(duì)基本概念加以敘述。
1.1 先在解決方案中創(chuàng)建一個(gè)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類型必須可以實(shí)例化
- {
- //根據(jù)條件獲取實(shí)體對(duì)象集合
- IQueryable<T> LoadEntites(Func<T,bool> whereLambda );
- //根據(jù)條件獲取實(shí)體對(duì)象集合分頁
- 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);
- }
- }
此時(shí)基接口中的CRUD方法就定義完成。接下來我們需要使用T4模版生成所有的實(shí)體類接口并實(shí)現(xiàn)IBaseDao接口。
三、生成所有的實(shí)體類接口
3.1 添加名為IDaoExt 的T4文本模版
3.2 在模版中貼入以下代碼,其中注釋的地方需要根據(jù)各自的項(xiàng)目進(jìn)行更改
- <#@ 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實(shí)體模型所在的路徑
- 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 //實(shí)體類接口所在的命名空間
- {
- <#
- foreach (EntityType entity in ItemCollection.GetItems<EntityType>().OrderBy(e => e.Name)) //便利edmx模型中映射的實(shí)體對(duì)象
- {#>
- public interface I<#=entity.Name#>Dao:IBaseDao<<#=entity.Name#>> //生成實(shí)體對(duì)象接口
- {
- }
- <#};#>
- }
3.3 T4模版編輯完成后,Ctrl+s保存,提示是否運(yùn)行,點(diǎn)擊確認(rèn)。此時(shí)就自動(dòng)幫我們生成了所有的實(shí)體類接口,并實(shí)現(xiàn)了IBaseDao接口,相應(yīng)的也具有了CRUD方法定義。
原文鏈接:http://www.cnblogs.com/rdst/archive/2012/08/12/2634159.html