首页 > 其他 > 详细

T4 模板代码示例

时间:2014-09-26 17:20:49      阅读:380      评论:0      收藏:0      [点我收藏+]

本模板可以根据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 <\u0023@ 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;
}
#>

  

T4 模板代码示例

原文:http://www.cnblogs.com/scottpeng/p/3994635.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!