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#

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

using SlnMesnac.Generate.Templates.Service;
using SlnMesnac.Generate.Templates.Service.Impl;
using SqlSugar;
using System;
#region << 版 本 注 释 >>
/*--------------------------------------------------------------------
* 版权所有 (c) 2024 WenJY 保留所有权利。
* CLR版本4.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);
}
}
}