62 lines
2.0 KiB
C#
Raw Normal View History

2021-09-07 18:37:21 +08:00
using Infrastructure;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
2021-09-07 18:37:21 +08:00
using System.Threading.Tasks;
namespace ZR.CodeGenerator
{
2021-09-19 11:36:52 +08:00
/// <summary>
/// 代码生成数据库连接
/// </summary>
2021-09-07 18:37:21 +08:00
public class DbProvider
{
protected static SqlSugarScope CodeDb;
2021-09-07 18:37:21 +08:00
/// <summary>
/// 获取动态连接字符串
/// </summary>
/// <param name="dbName">数据库名</param>
/// <returns></returns>
public SqlSugarScope GetSugarDbContext(string dbName = "")
2021-09-07 18:37:21 +08:00
{
2021-09-19 20:50:49 +08:00
string connStr = ConfigUtils.Instance.GetConfig(GenConstants.Gen_conn);
int dbType = ConfigUtils.Instance.GetAppConfig(GenConstants.Gen_conn_dbType, 0);
if (!string.IsNullOrEmpty(dbName))
{
string replaceStr = GetValue(connStr, "database=", ";");
connStr = connStr.Replace(replaceStr, dbName);
}
var db = new SqlSugarScope(new List<ConnectionConfig>()
2021-09-07 18:37:21 +08:00
{
new ConnectionConfig(){
ConnectionString = connStr,
DbType = (DbType)dbType,
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)
{
Regex rg = new Regex("(?<=(" + s + "))[.\\s\\S]*?(?=(" + e + "))", RegexOptions.Multiline | RegexOptions.Singleline);
return rg.Match(str).Value;
}
2021-09-07 18:37:21 +08:00
}
}