EF+T4 实现 Service 代码生成(多个文件)
生成效果:
//------------------------------------------------------------------------------ // <auto-generated> // 此代码是根据模板生成的。 // // 手动更改此文件可能会导致应用程序中发生异常行为。 // 如果重新生成代码,则将覆盖对此文件的手动更改。 // </auto-generated> //------------------------------------------------------------------------------ using DotNetMVC.IService; using DotNetMVC.Model; namespace DotNetMVC.Service { public partial class AdminUserService: BaseService<AdminUser>, IAdminUserService { public AdminUserService(DotNetMVCEntities Db) : base(Db) { } } }
T4Service.tt
<#@ template language="C#" debug="false" hostspecific="true"#> <#@ include file="EF6.Utility.CS.ttinclude"#><#@ output extension=".cs"#><# const string inputFile = @"../DotNetMVC.OA.Model/DataModel.edmx"; var textTransform = DynamicTextTransformation.Create(this); var code = new CodeGenerationTools(this); var ef = new MetadataTools(this); var typeMapper = new TypeMapper(code, ef, textTransform.Errors); var fileManager = EntityFrameworkTemplateFileManager.Create(this); var itemCollection = new EdmMetadataLoader(textTransform.Host, textTransform.Errors).CreateEdmItemCollection(inputFile); #> //------------------------------------------------------------------------------ // <auto-generated> // 此代码已从模板生成。 // // 手动更改此文件可能导致应用程序出现意外的行为。 // 如果重新生成代码,将覆盖对此文件的手动更改。 // </auto-generated> //------------------------------------------------------------------------------ using DotNetMVC.OA.IBLL; using DotNetMVC.OA.Model; namespace DotNetMVC.OA.BLL { <# //foreach begin foreach (var entity in typeMapper.GetItemsToGenerate<EntityType>(itemCollection)) { //fileManager.StartNewFile(entity.Name + ".cs"); //BeginNamespace(code); #> public partial class <#= entity.Name #>Service : BaseService<<#= entity.Name #>>, I<#= entity.Name #>Service { public override void SetCurrentDal() { CurrentDal = this.DbSession.<#= entity.Name #>Dal; } } <# //foreach end } #> } <#+ public class TypeMapper { private const string ExternalTypeNameAttributeName = @"http://schemas.microsoft.com/ado/2006/04/codegeneration:ExternalTypeName"; private readonly System.Collections.IList _errors; private readonly CodeGenerationTools _code; private readonly MetadataTools _ef; public TypeMapper(CodeGenerationTools code, MetadataTools ef, System.Collections.IList errors) { ArgumentNotNull(code, "code"); ArgumentNotNull(ef, "ef"); ArgumentNotNull(errors, "errors"); _code = code; _ef = ef; _errors = errors; } public IEnumerable<T> GetItemsToGenerate<T>(IEnumerable<GlobalItem> itemCollection) where T: EdmType { return itemCollection .OfType<T>() .Where(i => !i.MetadataProperties.Any(p => p.Name == ExternalTypeNameAttributeName)) .OrderBy(i => i.Name); } } public static void ArgumentNotNull<T>(T arg, string name) where T : class { if (arg == null) { throw new ArgumentNullException(name); } } #>