文件模板代码
<#@ template language="C#" #> <#@ output extension=".cs" #> <#@ assembly name="System.Core" #> <#@ import namespace="System.IO" #> <#@ import namespace="System.Linq" #> <#@ import namespace="System.Collections.Generic" #> <#@ import namespace="System.Text.RegularExpressions" #> <# // 设置生成的文件路径 string dbContextFilePath = @"XXX\Models\DbContext.cs"; string entityFolderPath = @"XXX\Models";// 实体类文件所在文件夹路径 string dbContextCode = File.ReadAllText(dbContextFilePath); var entityDic = new Dictionary<string, Dictionary<string, string>>(); // 正则匹配:表名,表注释 var entityMatches = Regex.Matches(dbContextCode, @"modelBuilder\.Entity<(.+?)>\(entity =>(.+?)entity\.HasComment\(""(.+?)""\);(.+?)\}", RegexOptions.Singleline); foreach (Match matchEntity in entityMatches) { var entityName = matchEntity.Groups[1].Value; var itemDic = new Dictionary<string, string> { { $"Table - {entityName}", matchEntity.Groups[3].Value} }; entityDic.Add(entityName, itemDic); // 正则匹配:字典名,字典注释 var propertyCode = matchEntity.Groups[4].Value; var propertyMatches = Regex.Matches(propertyCode, @"entity\.Property\(e => e\.(.+?)\)(.+?)\.HasComment\(""(.+?)""\);", RegexOptions.Singleline); foreach (Match matchProperty in propertyMatches) { itemDic.Add(matchProperty.Groups[1].Value, matchProperty.Groups[3].Value); } } // 获取实体类文件夹中的所有文件路径 string[] entityFiles = Directory.GetFiles(entityFolderPath, "*.cs"); // 遍历所有实体类文件,为每个文件添加注释 foreach (var entityFile in entityFiles) { // 排除dbContext文件 if(entityFile == dbContextFilePath) continue; string entityCode = File.ReadAllText(entityFile); // 过滤不存在的字典值 var entityName = Path.GetFileNameWithoutExtension(entityFile); if (!entityDic.ContainsKey(entityName)) continue; var itemDic = entityDic[entityName]; // 匹配实体类的注释 var updatedEntityCode = entityCode.Replace(" public partial class ", $@" /// <summary> /// {itemDic[$"Table - {entityName}"]} /// </summary> public partial class "); // 匹配实体类的属性并检查是否有注释 updatedEntityCode = Regex.Replace(updatedEntityCode, @"public (.+?) (.+?) \{ get; set; \}", match => { var propertyDeclaration = match.Value.Trim(); var itemPropertyCode = match.Groups[2].Value; if (itemDic.ContainsKey(itemPropertyCode)) { return $@" /// <summary> /// {itemDic[itemPropertyCode]} /// </summary> {propertyDeclaration}"; } return propertyDeclaration; // 已有注释则不修改 }); // 输出更新后的实体类代码 //Write(updatedEntityCode); // 写入更新后的实体类代码到同一文件中 File.WriteAllText(entityFile, updatedEntityCode); } #>
Remind
1.基于现有的DbContext文件,如果DbFirst生成结果有变化,需要重新调整正则2.没有过滤重复生成,多次保存会导致注释重复
Reference
NetCore EFCore DbFirst 连接 MsSql
标签:.+,T4,itemDic,Value,注释,EFCore,var,Net6,entityName From: https://www.cnblogs.com/CRobot/p/18254283