using Fluid; using System; using System.Collections.Generic; using System.IO; using System.Text; partial class Program { static void Main() { //发布的目录和项目的目录有区别的 var rootPath = AppContext.BaseDirectory.Replace(@"\bin\net8.0\", "").Replace(@"\bin\Release\net8.0\", ""); var templateFolderPath = Path.Combine(rootPath, "Template"); var outPutTemplateFolderPath = Path.Combine(rootPath, "TemplateOutPut"); #region 生成文件目录准备 if (!Directory.Exists(outPutTemplateFolderPath)) { Directory.CreateDirectory(outPutTemplateFolderPath); } var servicePath = Path.Combine(outPutTemplateFolderPath, "Service"); var iServicePath = Path.Combine(outPutTemplateFolderPath, "IService"); var entityPath = Path.Combine(outPutTemplateFolderPath, "Entity"); var dtoPath = Path.Combine(outPutTemplateFolderPath, "DTO"); if (!Directory.Exists(servicePath)) { Directory.CreateDirectory(servicePath); } if (!Directory.Exists(iServicePath)) { Directory.CreateDirectory(iServicePath); } if (!Directory.Exists(entityPath)) { Directory.CreateDirectory(entityPath); } if (!Directory.Exists(dtoPath)) { Directory.CreateDirectory(dtoPath); } #endregion // 要生成的表名数组 var tableNames = new List { "User", "Product", "Order" }; try { //便利所有模板文件进行生成操作 foreach (var templateFilePath in Directory.GetFiles(templateFolderPath)) { var fileName=Path.GetFileNameWithoutExtension(templateFilePath); foreach (var tableName in tableNames) { var model = new TemplateModel { TableName = tableName, IsPaged = true }; var parser = new FluidParser(); var source = File.ReadAllText(templateFilePath); if (parser.TryParse(source, out var template, out var error)) { var context = new TemplateContext(model); //Console.WriteLine(template.Render(context)); string outputFilePath = Path.Combine(outPutTemplateFolderPath, $"{fileName.Replace("Entity", tableName)}.cs"); File.WriteAllText(outputFilePath, template.Render(context)); } else { Console.WriteLine($"Error: {error}"); } } } } catch (Exception ex) { Console.WriteLine($"Error: {ex.Message}"); } } // Model class to pass data to the template public class TemplateModel { public string TableName { get; set; } //生成的列表是是分页 还是不分页 public bool IsPaged { get; set; } // 列表视图模型名称 public string TableNameView => TableName + "View"; //列表查询模型名称 public string TableNameQuery => TableName + "Query"; //添加和编辑模型名称 public string TableNameAddOrEdit => TableName + "AddOrEdit"; //删除主键属性名 public string LowercaseTableNameId => char.ToLower(TableName[0]) + TableName.Substring(1) + "Id"; public string LowercaseRepositoryName => $"_{char.ToLower(TableName[0]) + TableName.Substring(1)}Repository" ; public string LowercaseQueryableName => $"{char.ToLower(TableName[0]) + TableName.Substring(1)}Queryable"; public DateTime DateTimeNow = DateTime.Now; } }