.net core 通过Sqlsugar生成实体

通过替换字符串的方式生成代码,其他代码也可以通这种方式生成

直接上代码

设置模板

将这几个模板文件设置为:嵌入资源

模板内容:

csharp 复制代码
using SqlSugar;

namespace {Namespace}.Domain.Admin.{ModelName};
/// <summary>
/// {TableDisplayName}
///</summary>
[SugarTable("{TableName}")]
public class {ModelName}Entity
{
    {AttributeList}
}

生成代码

csharp 复制代码
 /// <summary>
 /// 预览代码
 /// </summary>
 /// <param name="currentTableName">表名</param>
 /// <returns></returns>
 [HttpGet]
 public ProviewCodeOutput PreviewCode(string currentTableName)
 {
 	  //我是在其他类里面生成的代码,所以通过dll加载嵌入的资源
     // 通过 DLL 加载资源 
     var assemblyPath = Path.Combine(AppContext.BaseDirectory, "XR.Host.dll");

     var assembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(assemblyPath);

     var resourceName = assembly.GetManifestResourceNames().FirstOrDefault(a => a.Contains("ModelTemplate.txt"));

     var file = assembly.GetManifestResourceStream(resourceName);
     //实体模板
     var modelTemplate = new StreamReader(file).ReadToEnd();
     //仓储接口模板
     var IrepostoryTemplate = new StreamReader(
         assembly.GetManifestResourceStream(assembly.GetManifestResourceNames().FirstOrDefault(a => a.Contains("IRepositoryTemplate.txt")))
         ).ReadToEnd();
     //仓储接口模板
     var repostoryTemplate = new StreamReader(
         assembly.GetManifestResourceStream(assembly.GetManifestResourceNames().Where(a => a.Contains("RepositoryClassTemplate.txt")).First())
         ).ReadToEnd();


     var orm = LazyGetRequiredService<IUserRepository>().Orm;

     var table = orm.DbMaintenance.GetTableInfoList(true);

     //命名空间
     var Namespace = Assembly.GetExecutingAssembly().GetName().Name;

     var parentPath = new DirectoryInfo(Environment.CurrentDirectory).Parent + $"\\{Namespace}";

     var result = new ProviewCodeOutput();

     foreach (var tableInfo in table)
     {
         if (tableInfo.Name == currentTableName)
         {
             var modelName = tableInfo.Name.Replace("SYS_", "").Replace("TB_", "").Replace("TN_", "");
             modelName = ConvertToCamelCase(modelName);

             var tableColumn = orm.DbMaintenance.GetColumnInfosByTableName(tableInfo.Name);
             var attributes = BuildColumn(tableColumn);
			//通过替换字符串的方式生成代码
             result.ModalCode = modelTemplate.Replace("{Namespace}", Namespace)
                 .Replace("{ModelName}", modelName)
                 .Replace("{TableName}", tableInfo.Name)
                 .Replace("{TableDisplayName}", tableInfo.Description)
                 .Replace("{AttributeList}", attributes);

         }
     }
     return result;
 }
 private string BuildColumn(List<DbColumnInfo> columnInfos)
 {
     var attributes = new StringBuilder();
     foreach (var columnInfo in columnInfos)
     {
         attributes.Append("\r\n    /// <summary>");
         attributes.Append($"\r\n   /// {columnInfo.ColumnDescription}");
         attributes.Append("\r\n    /// </summary>");
         attributes.Append($"\r\n   [SugarColumn({(columnInfo.IsPrimarykey ? "IsPrimaryKey = true," : "")} ColumnName = \"{columnInfo.DbColumnName}\", {(columnInfo.IsNullable ? "IsNullable = true," : "")} ColumnDescription = \"{columnInfo.ColumnDescription}\")]");
         attributes.Append($"\r\n   public {SetDataType(columnInfo.DataType)}{(columnInfo.IsNullable ? "?" : "")} {ConvertToCamelCase(columnInfo.DbColumnName)} {{ get; set; }}");

     }
     return attributes.ToString();
 }
 private string SetDataType(string dataType)
 {
     dataType = dataType.ToLower();
     var result = dataType;
     switch (dataType)
     {
         case "int32":
             result = typeof(int).Name;
             break;
         case "int64":
             result = typeof(int).Name;
             break;
         case "datetime":
             result = typeof(DateTime).Name;
             break;
     }
     return result;
 }
 /// <summary>
 /// 将驼峰转换为字符串
 /// </summary>
 /// <param name="input"></param>
 /// <returns></returns>
 private string ConvertToCamelCase(string input)
 {
     if (string.IsNullOrEmpty(input))
         return input;
     var text = input.Split('_');
     var camelTxt = "";
     TextInfo textInfo = CultureInfo.CurrentCulture.TextInfo;
     foreach (var c in text)
     {
         camelTxt += textInfo.ToTitleCase(c.ToLower());
     }
     return camelTxt;
 }
相关推荐
武藤一雄3 天前
C#常见面试题100问 (第一弹)
windows·microsoft·面试·c#·.net·.netcore
猹叉叉(学习版)5 天前
【ASP.NET CORE】 14. RabbitMQ、洋葱架构
笔记·后端·架构·c#·rabbitmq·asp.net·.netcore
Murphy20236 天前
.NetCore项目使用EF Core操作SQL Server
.netcore
码界奇点7 天前
基于.NET Core的CMS内容管理系统设计与实现
c++·毕业设计·.netcore·源代码管理
猹叉叉(学习版)7 天前
【ASP.NET CORE】 13. DDD初步实现
笔记·后端·架构·c#·asp.net·.netcore
武藤一雄7 天前
WPF Command 设计思想与实现剖析
windows·微软·c#·.net·wpf·.netcore
武藤一雄7 天前
WPF 资源解析:StaticResource & DynamicResource 实战指南
微软·c#·.net·wpf·.netcore
武藤一雄7 天前
WPF UI 开发深度指南:资源 (Resources)、样式 (Style) 与触发器 (Trigger) 全解析
ui·c#·.net·wpf·.netcore·avalonia
吹牛不交税7 天前
vue3项目部署到阿里云Alibaba Cloud Linux3系统的docker
docker·容器·.netcore
猹叉叉(学习版)8 天前
【ASP.NET CORE】 12. DDD基本概念
笔记·后端·架构·c#·asp.net·.netcore