项目版本为 NetCore5.0
新建一个控制台项目
首先 安装 包 RazorEngine.NetCore
固定配置 别问 问就是 就这么敲
var config = new TemplateServiceConfiguration(); config.Debug = true; config.EncodedStringFactory = new RawStringFactory(); var service = RazorEngineService.Create(config);
然后是 模板文件
using System; namespace Test.Model { public class @(Model.Name) { @foreach (var item in Model.Columns) { @*@(public {item.pro} {item.Name}{{get;set;}})*@ @($@" public {item.Pro} { item.ColumnName} {{ get; set; }} ") } } }
读取模板 生成代码
var baseDir = AppDomain.CurrentDomain.BaseDirectory; string templateDir = Path.Combine(baseDir, "Templates"); var files = Directory.GetFiles(templateDir, "*", SearchOption.AllDirectories); Dictionary<string, string> templist = new Dictionary<string, string>(); foreach (var item in files) { templist.Add(Path.GetFileNameWithoutExtension(item) , File.ReadAllText(item)); } var entity = new EFTable() { Name="TestModel", Columns=new List<EFColumn>() { new EFColumn(){ Pro="string",ColumnName="Id" }, new EFColumn(){ Pro="string",ColumnName="Name" } } }; DataContext ctx = new DataContext(); foreach (var item in templist) { var result=service.RunCompile(item.Value,item.Key,null,entity); }
result 就是生成的文本 将文本写入文件 就达到了直接生成项目文件的目的
Model 文件
public class EFTable { public string Name { get; set; } public List<EFColumn> Columns { get; set; } public string Constructor { get; internal set; } public object References { get; internal set; } } public class EFColumn { public string Name { get; set; } public string Pro { get; set; } public string Comment { get; set; } public string ColumnName { get; set; } public bool IsPrimaryKey { get; set; } public bool IsNullable { get; set; } public int? MaxLength { get; set; } }
最后 在写入文件就好了
File.WriteAllText(savePath, result);