You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

114 lines
3.5 KiB
C#

2 months ago
using SlnMesnac.Generate.Templates.Service;
using SlnMesnac.Generate.Templates.Service.Impl;
using SqlSugar;
using System;
#region << 版 本 注 释 >>
/*--------------------------------------------------------------------
* (c) 2024 WenJY
* CLR4.0.30319.42000
* LAPTOP-E0N2L34V
* SlnMesnac.Generate
* 78595105-fab6-40f0-97b4-1272dc3e0e86
*
* WenJY
* wenjy@mesnac.com
* 2024-04-11 13:35:01
* V1.0.0
*
*
*--------------------------------------------------------------------
*
*
*
*
* V1.0.0
*--------------------------------------------------------------------*/
#endregion << 版 本 注 释 >>
namespace SlnMesnac.Generate
{
/// <summary>
/// 生成代码
/// </summary>
public class GenerateCode
{
private readonly ISqlSugarClient _sqlSugarClient;
public GenerateCode(ISqlSugarClient sqlSugarClient)
{
_sqlSugarClient = sqlSugarClient;
}
public bool CreateCode(string configId,string tableName,string savePath,string nameSpace)
{
if (string.IsNullOrEmpty(configId))
{
throw new ArgumentNullException($"代码生成异常:configId参数为空");
}
if (string.IsNullOrEmpty(tableName))
{
throw new ArgumentNullException($"代码生成异常:表格名称参数为空");
}
if (string.IsNullOrEmpty(savePath))
{
throw new ArgumentNullException($"代码生成异常:文件存储路径参数为空");
}
if (string.IsNullOrEmpty(nameSpace))
{
throw new ArgumentNullException($"代码生成异常:命名空间参数为空");
}
try
{
savePath += $"\\{tableName}";
var scope = _sqlSugarClient.AsTenant().GetConnectionScope(configId);
scope.DbFirst.IsCreateAttribute()
.FormatPropertyName(it=> ToCamelCase(it)).Where(p => p == tableName).CreateClassFile($"{savePath}\\Entity", nameSpace);
var isc = new IServiceCreate();
bool iscRes = isc.Create(tableName, nameSpace, savePath);
if (!iscRes)
{
throw new InvalidOperationException($"Service接口生成失败");
}
var sc = new ServiceCreate();
var scRes = sc.Create(tableName, nameSpace, savePath);
if (!scRes)
{
throw new InvalidOperationException($"Service实现类生成失败");
}
return true;
}catch (Exception ex)
{
throw new InvalidOperationException($"代码生成异常:{ex.Message}");
}
}
private static string ToCamelCase(string input)
{
// 将字符串转换为驼峰格式,但保持每个单词的首字母大写
string[] words = input.Split('_');
for (int i = 0; i < words.Length; i++)
{
if (i > 0)
{
words[i] = char.ToUpper(words[i][0]) + words[i].Substring(1).ToLower();
}
else
{
words[i] = words[i].ToLower();
}
}
return string.Join("", words);
}
}
}