68 lines
2.3 KiB
C#
Raw Normal View History

2021-09-07 18:37:21 +08:00
using Infrastructure;
2022-06-01 17:36:06 +08:00
using Infrastructure.Extensions;
2021-09-07 18:37:21 +08:00
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
2021-09-07 18:37:21 +08:00
namespace ZR.CodeGenerator
{
2021-09-19 11:36:52 +08:00
/// <summary>
/// 代码生成数据库连接
/// </summary>
2021-09-07 18:37:21 +08:00
public class DbProvider
{
2021-12-11 16:37:08 +08:00
protected static SqlSugarClient CodeDb;
2021-09-07 18:37:21 +08:00
/// <summary>
/// 获取动态连接字符串
/// </summary>
/// <param name="dbName">数据库名</param>
/// <returns></returns>
2021-12-11 16:37:08 +08:00
public SqlSugarClient GetSugarDbContext(string dbName = "")
2021-09-07 18:37:21 +08:00
{
2023-04-07 10:58:24 +08:00
Gen options = new();
AppSettings.Bind("gen", options);
string connStr = options.Conn;
if (!string.IsNullOrEmpty(dbName))
{
2023-04-07 10:58:24 +08:00
string replaceStr = GetValue(options.Conn, "Database=", ";");
string replaceStr2 = GetValue(options.Conn, "Initial Catalog=", ";");
2022-06-01 17:36:06 +08:00
if (replaceStr.IsNotEmpty())
{
2023-04-07 10:58:24 +08:00
connStr = options.Conn.Replace(replaceStr, dbName, StringComparison.OrdinalIgnoreCase);
2022-06-01 17:36:06 +08:00
}
if (replaceStr2.IsNotEmpty())
{
2023-04-07 10:58:24 +08:00
connStr = options.Conn.Replace(replaceStr2, dbName, StringComparison.OrdinalIgnoreCase);
}
}
2021-12-11 16:37:08 +08:00
var db = new SqlSugarClient(new List<ConnectionConfig>()
2021-09-07 18:37:21 +08:00
{
new ConnectionConfig(){
ConnectionString = connStr,
2023-04-07 10:58:24 +08:00
DbType = (DbType)options.DbType,
2021-09-07 18:37:21 +08:00
IsAutoCloseConnection = true,//开启自动释放模式和EF原理一样
InitKeyType = InitKeyType.Attribute,//从特性读取主键和自增列信息
},
});
CodeDb = db;
return db;
2021-09-07 18:37:21 +08:00
}
/// <summary>
/// 获得字符串中开始和结束字符串中间得值
/// </summary>
/// <param name="str">字符串</param>
/// <param name="s">开始</param>
/// <param name="e">结束</param>
/// <returns></returns>
public static string GetValue(string str, string s, string e)
{
2023-04-07 10:58:24 +08:00
Regex rg = new("(?<=(" + s + "))[.\\s\\S]*?(?=(" + e + "))", RegexOptions.Multiline | RegexOptions.Singleline);
return rg.Match(str).Value;
}
2021-09-07 18:37:21 +08:00
}
}