T4 模板代码示例

本模板可以根据EF框架的edmx文件生成多个Respository类文件

<#@ template language="C#" debug="true" hostspecific="true"#>
<#@ include file="EF.Utility.CS.ttinclude"#>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.Diagnostics" #>

<#@ output extension=".cs"#>
<#

// This needs to be set to the .edmx file that you want to process.
//string edmxFile = FindEDMXFileName(); // @"Model1.edmx";
string edmxFile = @"Model.edmx";
CodeGenerationTools code = new CodeGenerationTools(this);
MetadataLoader loader = new MetadataLoader(this);
MetadataTools ef = new MetadataTools(this);

#>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions; 

namespace <#= code.VsNamespaceSuggestion() #>
{
	public interface IRepository<T>
    {
		IUnitOfWork UnitOfWork { get; set; }
		bool IsUseDataFilter{get;set;}
		IQueryable<T> All();
		IQueryable<T> Find(Expression<Func<T, bool>> expression);
		IQueryable<T> Find(string where , params object[] para);
		IQueryable<T> Sort(IQueryable<T> source, string sortfield);
		void Add(T entity);
		void Delete(T entity);
		void Save();
		void Update(T entity);
    }
}<#

EdmItemCollection ItemCollection = loader.CreateEdmItemCollection(edmxFile);
EntityContainer container = ItemCollection.GetItems<EntityContainer>().FirstOrDefault();
EntityFrameworkTemplateFileManager fileManager = EntityFrameworkTemplateFileManager.Create(this);

foreach (EntityType entity in ItemCollection.GetItems<EntityType>().OrderBy(e => e.Name))
{;
    fileManager.StartNewFile(entity.Name + "Repository.Generated.cs"); #>using System;
using System.Linq;
using System.Collections.Generic;

// This file is auto generated and will be overwritten as soon as the template is executed
// Do not modify this file...

namespace <#= code.VsNamespaceSuggestion() #>
{
	<#=Accessibility.ForType(entity)#> <#=code.SpaceAfter(code.AbstractOption(entity))#>partial class <#=code.Escape(entity)#>Repository
	{
		private IRepository<<#=code.Escape(entity)#>> _repository {get;set;}
		private bool _isUseDataFilter;
		public IRepository<<#=code.Escape(entity)#>> Repository
		{
			get { return _repository; }
			set { _repository = value; }
		}

		public <#=code.Escape(entity)#>Repository(IRepository<<#=code.Escape(entity)#>> repository, IUnitOfWork unitOfWork)
    	{
    		Repository = repository;
			Repository.UnitOfWork = unitOfWork;
			IsUseDataFilter = true;
    	}

		public IQueryable<<#=code.Escape(entity)#>> All()
		{
			return Repository.All();
		}

		public void Add(<#=code.Escape(entity)#> entity)
		{
			throw new NotImplementedException("This repository does not support the method.");
		}

		public void Delete(<#=code.Escape(entity)#> entity)
		{
			throw new NotImplementedException("This repository does not support the method.");
		}

		public void Save()
		{
			throw new NotImplementedException("This repository does not support the method.");
		}

		public bool IsUseDataFilter
        {
            get
            {
                return _isUseDataFilter;
            }
            set
            {
                _isUseDataFilter = value;
				this.Repository.IsUseDataFilter = value;
            }
        }
	}
}<#
	if(!DoesFileExist(entity.Name + "Repository.cs"))
	{
		fileManager.StartNewFile(entity.Name + "Repository.cs");
		#>using System;
using System.Linq;
using System.Collections.Generic;

namespace <#= code.VsNamespaceSuggestion() #>
{
	<#=Accessibility.ForType(entity)#> <#=code.SpaceAfter(code.AbstractOption(entity))#>partial class <#=code.Escape(entity)#>Repository
	{
		// Add your own data access methods.
		// This file should not get overridden
	}
}<#
	}
	else
	{
		fileManager.StartNewFile(entity.Name + "Repository.cs");
		this.Write(OutputFile(entity.Name + "Repository.cs"));
	}
}

fileManager.StartNewFile("IUnitOfWork.cs");
#>using System.Data.Objects;

namespace <#= code.VsNamespaceSuggestion() #>
{
	public interface IUnitOfWork
	{
		ObjectContext Context { get; set; }
		void Save();
		bool LazyLoadingEnabled { get; set; }
		bool ProxyCreationEnabled { get; set; }
		string ConnectionString { get; set; }
	}
}<#	fileManager.StartNewFile("RepositoryIQueryableExtensions.cs");
#>using System.Data.Objects;
using System.Linq;

namespace <#= code.VsNamespaceSuggestion() #>
{
	public static class RepositoryIQueryableExtensions
	{
		public static IQueryable<T> Include<T>
			(this IQueryable<T> source, string path)
		{
			var objectQuery = source as ObjectQuery<T>;
			if (objectQuery != null)
			{
				return objectQuery.Include(path);
			}
			return source;
		}
	}
}<# fileManager.StartNewFile("EFRepository.cs");
#>using System;
using System.Collections.Generic;
using System.Data.Objects;
using System.Linq;
using System.Text;
using System.Linq.Dynamic;
using System.Linq.Expressions;
using SCM.SCMEntity;

namespace <#= code.VsNamespaceSuggestion() #>
{
	public class EFRepository<T> : IRepository<T> where T : class
	{
		public IUnitOfWork UnitOfWork { get; set; }
		public bool IsUseDataFilter { get; set; }
		private IObjectSet<T> _objectset;
		private IObjectSet<T> ObjectSet
		{
			get
			{
				if (_objectset == null)
				{
					_objectset = UnitOfWork.Context.CreateObjectSet<T>();
				}
				return _objectset;
			}
		}

        public virtual void Update(T entity)
        {

            UnitOfWork.Context.ApplyCurrentValues<T>(typeof(T).Name,entity);
            UnitOfWork.Save();
        }

		public virtual IQueryable<T> All()
		{
			IQueryable<T> iq = ObjectSet.AsQueryable(); ;

            ApplyDataFilter(ref iq);

            return iq;
		}

		public IQueryable<T> Find(string where , params object[] paras)
        {
            IQueryable<T> iq =ObjectSet.Where(where , paras).AsQueryable();

            ApplyDataFilter(ref iq);

			return iq;
        }

		public IQueryable<T> Find(Expression<Func<T, bool>> expression)
		{
			IQueryable<T> iq = ObjectSet.Where<T>(expression).AsQueryable();

            ApplyDataFilter(ref iq);

			return iq;
		}

		public IQueryable<T> Sort(IQueryable<T> source,string sortfield)
        {
            return source.OrderBy(sortfield);
        }

		public void Add(T entity)
		{
			ObjectSet.AddObject(entity);
		}

		public void Delete(T entity)
		{
			ObjectSet.DeleteObject(entity);
		}

		public void Save()
		{
			UnitOfWork.Save();
		}

        private void ApplyDataFilter(ref IQueryable<T> iq)
        {
            if (IsUseDataFilter==null||!IsUseDataFilter)
                return;

            var context = new SCM.SCMEntity.SCMEntity();
            IObjectSet<sysDataFilter> _df = context.CreateObjectSet<sysDataFilter>();

            if (System.Web.HttpContext.Current == null)
                return;

            if (System.Web.HttpContext.Current.Session["userid"] == null)
                return;

            string userid=System.Web.HttpContext.Current.Session["userid"].ToString();

            List<sysDataFilter> dfs =_df.Where<sysDataFilter>(p=>p.UserID==userid&&p.TableID==typeof(T).Name).AsQueryable<sysDataFilter>().ToList();;
            var totalexp = iq.Expression;

            if (dfs == null)
                return;

            if (dfs.Count > 0)
            {
                var para = Expression.Parameter(typeof(T), "p");
                foreach (sysDataFilter df in dfs)
                {
                    var bin = Expression.Property(para, df.FieldName);

                    Type t=bin.Type;
                    #region Calculate expression
                    switch (df.FOperator)
                    {
                        case "=":

                            var con1 = Expression.Constant(df.FParameter,bin.Type);
                            var bin1 = Expression.Equal(bin, con1);
                            var ex1 = Expression.Lambda<Func<T, bool>>(bin1, para);
							try
							{
								switch(df.AndOr.ToLower())
								{
									case "and":
										totalexp = Expression.And(bin1, totalexp);
										break;
									case "or":
										totalexp = Expression.Or(bin1,totalexp);
										break;
									default:
										totalexp=bin1;
										break;
								}
							}catch { totalexp = bin1;}
                            break;
                        case ">":

                            var con2 = Expression.Constant(df.FParameter, bin.Type);
                            var bin2 = Expression.GreaterThan(bin, con2);
                            var ex2 = Expression.Lambda<Func<T, bool>>(bin2, para);
							try
							{
								switch (df.AndOr.ToLower())
								{
									case "and":
										totalexp = Expression.And(bin2, totalexp);
										break;
									case "or":
										totalexp = Expression.Or(bin2, totalexp);
										break;
									default:
										totalexp = bin2;
										break;
								}
                            }catch { totalexp = bin2;}
                            //iq = iq.Where<T>(ex2).AsQueryable();
                            break;
                        case "<":

                            var con3 = Expression.Constant(df.FParameter, bin.Type);
                            var bin3 = Expression.LessThan(bin, con3);
                            var ex3 = Expression.Lambda<Func<T, bool>>(bin3, para);
							try{
                            switch (df.AndOr.ToLower())
                            {
                                case "and":
                                    totalexp = Expression.And(bin3, totalexp);
                                    break;
                                case "or":
                                    totalexp = Expression.Or(bin3, totalexp);
                                    break;
                                default:
                                    totalexp = bin3;
                                    break;
                            }
                            }catch { totalexp = bin3;}
                            //iq = iq.Where<T>(ex3).AsQueryable();
                              break;
                              case "<>":

                              var con6 = Expression.Constant(df.FParameter, bin.Type);
                              var bin6 = Expression.LessThan(bin, con6);
                              var ex6 = Expression.Lambda<Func<T, bool>>(bin6, para);
                                try{
                                switch (df.AndOr.ToLower())
                                {
                                case "and":
                                totalexp = Expression.And(bin6, totalexp);
                                break;
                                case "or":
                                totalexp = Expression.Or(bin6, totalexp);
                                break;
                                default:
                                totalexp = bin6;
                                break;
                                }
                                }catch { totalexp = bin6;}
                                //iq = iq.Where<T>(ex6).AsQueryable();
                                  break;
                                  case "StartWith":
                                  var con4 = Expression.Constant(df.FParameter);
                                  var bin4 = Expression.LessThan(bin, con4);
                                  var ex4 = Expression.Lambda<Func<T, bool>>(bin4, para);
							try{
                            switch (df.AndOr.ToLower())
                            {
                                case "and":
                                    totalexp = Expression.And(bin4, totalexp);
                                    break;
                                case "or":
                                    totalexp = Expression.Or(bin4, totalexp);
                                    break;
                                default:
                                    totalexp = bin4;
                                    break;
                            }
                            }catch { totalexp = bin4;}
                            //iq = iq.Where<T>(ex4).AsQueryable();
                            break;
                        case "EndWith":
                            var con5 = Expression.Constant(df.FParameter);
                            var bin5 = Expression.LessThan(bin, con5);
                            var ex5 = Expression.Lambda<Func<T, bool>>(bin5, para);
							try{
                            switch (df.AndOr.ToLower())
                            {
                                case "and":
                                    totalexp = Expression.And(bin5, totalexp);
                                    break;
                                case "or":
                                    totalexp = Expression.Or(bin5, totalexp);
                                    break;
                                default:
                                    totalexp = bin5;
                                    break;
                            }
							}catch { totalexp = bin5;}
                            break;
                    }
                    #endregion
                }
                var exfinal = Expression.Lambda<Func<T, bool>>(totalexp, para);

                iq = iq.Where<T>(exfinal).AsQueryable();
            }
        }
	}
}<#fileManager.StartNewFile("EFUnitOfWork.cs");
#>using System.Data.Objects;

namespace <#= code.VsNamespaceSuggestion() #>
{
	public class EFUnitOfWork : IUnitOfWork
	{
		public ObjectContext Context { get; set; }

		public EFUnitOfWork()
		{
			Context = new <#=code.Escape(container)#>();
			Context.CommandTimeout=1800;
		}

		public EFUnitOfWork(int count)
		{
			Context = new <#=code.Escape(container)#>();
            Context.CommandTimeout = count;
		}

		public void Save()
		{
			Context.SaveChanges();
		}

		public bool LazyLoadingEnabled
		{
			get { return Context.ContextOptions.LazyLoadingEnabled; }
			set { Context.ContextOptions.LazyLoadingEnabled = value;}
		}

		public bool ProxyCreationEnabled
		{
			get { return Context.ContextOptions.ProxyCreationEnabled; }
			set { Context.ContextOptions.ProxyCreationEnabled = value; }
		}

		public string ConnectionString
		{
			get { return Context.Connection.ConnectionString; }
			set { Context.Connection.ConnectionString = value; }
		}
	}
}<#	fileManager.Process();
#>

<#+

bool DoesFileExist(string filename)
{
	return File.Exists(Path.Combine(GetCurrentDirectory(),filename));
}

string OutputFile(string filename)
{
	using(StreamReader sr = new StreamReader(Path.Combine(GetCurrentDirectory(),filename)))
	{
		string contents = sr.ReadToEnd();
		return contents;
	}
}

string GetCurrentDirectory()
{
	string executingDirectoryName = "";
	string stackTraceFileName = new StackTrace(true).GetFrame(0).GetFileName();
	if (String.IsNullOrEmpty(stackTraceFileName))
	{
		throw new ArgumentException("No value was specified for the ‘directoryName‘ configuration parameter" +
			", and we could not figure out the file name from the stack trace (most likely because of running " +
			"the template with debug=‘False‘ specified in the <\[email protected] template \u0023> directive.");
	}
	else
	{
		executingDirectoryName = Path.GetDirectoryName(stackTraceFileName);
	}
	return executingDirectoryName;
}

string FindEDMXFileName()
{
	string edmxFile = "";

	string[] entityFrameworkFiles = Directory.GetFiles(GetCurrentDirectory(), "*.edmx");
	if(entityFrameworkFiles.Length > 0)
		edmxFile = entityFrameworkFiles[0];

	return edmxFile;
}
#>

  

时间: 2024-10-16 10:22:43

T4 模板代码示例的相关文章

使用T4模板生成代码的学习

之前做项目使用的都是Db First,直接在项目中添加Entity Framework,使用T4模板(T4模板引擎之基础入门)生成DAL BLL层等(T4模板是一个同事给的,也没有仔细研究,代码如下:) <#@ template language="C#" debug="false" hostspecific="true"#> <#@ include file="EF.Utility.CS.ttinclude"

[转]MVC实用架构设计(三)——EF-Code First(3):使用T4模板生成相似代码

本文转自:http://www.cnblogs.com/guomingfeng/p/mvc-ef-t4.html 〇.目录 一.前言 二.工具准备 三.T4代码生成预热 (一) 单文件生成:HelloWorld.cs (二) 多文件生成 四.生成数据层实体相关相似代码 (一) 生成准备 (二) 生成实体相关相似代码 生成实体映射配置类 生成实体仓储接口 生成实体仓储实现 五.源码获取 系列导航 一.前言 经过前面EF的<第一篇>与<第二篇>,我们的数据层功能已经较为完善了,但有不少

T4模板:MVC中用T4模板快速生成代码

T4模板快速生成代码: 以快速生Dal文件为例,下面为T4模板文件的内容 <#@ template debug="false" hostspecific="true" language="C#" #> <#@ include file="EF.Utility.CS.ttinclude"#> <#@ output extension=".cs" #> <# CodeG

轻量级ORM 利用T4模板 批量生成多文件 实体和业务逻辑 代码

FluentData,它是一个轻量级框架,关注性能和易用性. 下载地址:FlunenData.Model 利用T4模板,[MultipleOutputHelper.ttinclude]批量生成多文件 基本语法: 1. 初始化:获取MultipleOutputHelper.ttinclude文件模板 在T4模板导入 //导入MultipleOutputHelper.ttinclude文件 路径 <#@include file="$(SolutionDir)\ORM.Model\T4\Mult

Ef+T4模板实现代码快速生成器

转载请注明地址:http://www.cnblogs.com/cainiaodage/p/4953601.html 效果如图,demo抛砖引玉,还望大家不吝赐教.(点击demo下载案例) 项目结构如图 T4BLL添加BLL.tt文件: T4Model添加Model文件: T4DAL添加DAL.tt文件: T4DAL 添加ADO.NET Entity Data Model选择dababase first 模式: 打开Model1.edmx文件下的Model1.tt打开,复制内容替换了T4Model

T4模板

T4,即4个T开头的英文字母组合:Text Template Transformation Toolkit. T4文本模板,即一种自定义规则的代码生成器.根据业务模型可生成任何形式的文本文件或供程序调用的字符串.(模型以适合于应用程序域的形式包含信息,并且可以在应用程序的生存期更改) VS本身只提供一套基于T4引擎的代码生成的执行环境,由下面程序集构成: Microsoft.VisualStudio.TextTemplating.10.0.dll Microsoft.VisualStudio.T

二、T4模板

上文带大家见识了下T4,这里呢开始介绍T4模板有关的内容.关于T4模板介绍和使用网上一搜一箩筐,想深入研究的可以自行去找些资料,这里只介绍接下来我们需要使用的一些知识,不会面面俱到的讲T4模板所有的知识.T4模板使用和ASPX文件使用方式近乎类似所以也不需要花太多时间. 打开TT文件,输入如下代码并保存: @ assembly 指明TT模板环境使用的目标程序集 @ import 指明TT模板环境使用的命名空间 @ output 指明TT模板输出格式,包括文件后缀编码方式等 <##>中包含的代码

你必须懂的 T4 模板:深入浅出

示例代码:示例代码__你必须懂的T4模板:浅入深出.rar (一)什么是T4模板? T4,即4个T开头的英文字母组合:Text Template Transformation Toolkit. T4文本模板,即一种自定义规则的代码生成器.根据业务模型可生成任何形式的文本文件或供程序调用的字符串.(模型以适合于应用程序域的形式包含信息,并且可以在应用程序的生存期更改) VS本身只提供一套基于T4引擎的代码生成的执行环境,由下面程序集构成: Microsoft.VisualStudio.TextTe

EF CodeFirst 使用T4模板

实用等级:★★★★★ 首先,定义一个接口,代表一个领域实体.在定义一个实体集成这个接口,面向接口编程的各种好处就不提了. /// <summary> /// 代表一个领域实体 /// </summary> public interface IEntity { Guid ID { get; } } public abstract class Entity : IEntity { public Guid ID { get; set; } //这里可以写一些领域实体的基本方法.面向对象么