2021-01-24

NVelocity实现代码生成

在框架开发过程中,通用代码生成是一项必不可少的功能,c#在这后端模板引擎这方面第三方组件较少,我这里选择的是NVelocity,现在升级到了NetStandard2.0,可以用于NetCore项目

添加引用


初始化模板引擎及设置模板读取路径

   vltEngine = new VelocityEngine();   vltEngine.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file");   vltEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, CloudUtil.GetContentPath() + "/" + "Template");   vltEngine.Init();


读取模板渲染结果

 VelocityContext vltContext = new VelocityContext();   foreach (var item in RenderDataDic)   {    vltContext.Put(item.Key, item.Value);   }   Template vltTemplate = vltEngine.GetTemplate(TemplateFileName);   System.IO.StringWriter vltWriter = new System.IO.StringWriter();   vltTemplate.Merge(vltContext, vltWriter);   string CodeContent = vltWriter.GetStringBuilder().ToString();


模板语法

示例Entity模板

using FastORM.Attribute;using FastORM.Entity;using System;using System.Collections.Generic;using System.Text;namespace ${NameSpace}.Entity{ [Table(Name = "${TablePhysicalNameLowCase}")] public class ${TablePhysicalName} : BaseEntity {  [Key]  public string RowGuid { set; get; }  #foreach( $Column in $ColumnList)  #if (($Column.ColumnType == 10 || $Column.ColumnType == 50) && $Column.PhysicalColumnName!="RowGuid")  public string $Column.PhysicalColumnName { set; get; }  

No comments:

Post a Comment