简化数据库操作

This commit is contained in:
不做码农 2022-05-12 21:28:27 +08:00
parent d503970db7
commit 8e24ac205c
5 changed files with 31 additions and 46 deletions

View File

@ -6,13 +6,6 @@ namespace Infrastructure
/// </summary> /// </summary>
public class OptionsSetting public class OptionsSetting
{ {
public static string ConnAdmin = "conn_zrAdmin";
public static string ConnDbType = "conn_zrAdmin_type";
public static string ConnBus = "conn_bus";
public static string ConnBusDbType = "conn_bus_type";
public string Redis { get; set; }
public string Database { get; set; }
/// <summary> /// <summary>
/// 是否演示模式 /// 是否演示模式
/// </summary> /// </summary>
@ -37,7 +30,6 @@ namespace Infrastructure
/// </summary> /// </summary>
public class Upload public class Upload
{ {
public string UploadDirectory { get; set; }
public string UploadUrl { get; set; } public string UploadUrl { get; set; }
} }
/// <summary> /// <summary>

View File

@ -237,7 +237,7 @@ namespace ZR.Admin.WebApi.Controllers
var genTableInfo = GenTableService.GetGenTableInfo(dto.TableId); var genTableInfo = GenTableService.GetGenTableInfo(dto.TableId);
genTableInfo.Columns = GenTableColumnService.GenTableColumns(dto.TableId); genTableInfo.Columns = GenTableColumnService.GenTableColumns(dto.TableId);
dto.DbType = AppSettings.GetAppConfig(OptionsSetting.ConnBusDbType, 0); dto.DbType = AppSettings.GetAppConfig("gen:dbType", 0);
dto.GenTable = genTableInfo; dto.GenTable = genTableInfo;
dto.IsPreview = true; dto.IsPreview = true;
//生成代码 //生成代码
@ -263,7 +263,7 @@ namespace ZR.Admin.WebApi.Controllers
var genTableInfo = GenTableService.GetGenTableInfo(dto.TableId); var genTableInfo = GenTableService.GetGenTableInfo(dto.TableId);
genTableInfo.Columns = GenTableColumnService.GenTableColumns(dto.TableId); genTableInfo.Columns = GenTableColumnService.GenTableColumns(dto.TableId);
dto.DbType = AppSettings.GetAppConfig(OptionsSetting.ConnBusDbType, 0); dto.DbType = AppSettings.GetAppConfig("gen:dbType", 0);
dto.GenTable = genTableInfo; dto.GenTable = genTableInfo;
//自定义路径 //自定义路径
if (genTableInfo.GenType == "1") if (genTableInfo.GenType == "1")

View File

@ -26,43 +26,43 @@ namespace ZR.Admin.WebApi.Extensions
public static void AddDb(IConfiguration Configuration) public static void AddDb(IConfiguration Configuration)
{ {
string connStr = Configuration.GetConnectionString(OptionsSetting.ConnAdmin); string connStr = Configuration.GetConnectionString("conn_db");
string connStrBus = Configuration.GetConnectionString(OptionsSetting.ConnBus); int dbType = Convert.ToInt32(Configuration["conn_db_dbtype"]);
int dbType = Convert.ToInt32(Configuration[OptionsSetting.ConnDbType]);
int dbType_bus = Convert.ToInt32(Configuration[OptionsSetting.ConnBusDbType]);
SugarIocServices.AddSqlSugar(new List<IocConfig>() { SugarIocServices.AddSqlSugar(new List<IocConfig>() {
new IocConfig() { new IocConfig() {
ConfigId = "0", ConfigId = "0",//默认db
ConnectionString = connStr, ConnectionString = connStr,
DbType = (IocDbType)dbType, DbType = (IocDbType)dbType,
IsAutoCloseConnection = true IsAutoCloseConnection = true
}, new IocConfig() { },
new IocConfig() {
ConfigId = "1", ConfigId = "1",
ConnectionString = connStrBus, ConnectionString = "替换成你的字符串",
DbType = (IocDbType)dbType_bus, DbType = IocDbType.MySql,
IsAutoCloseConnection = true IsAutoCloseConnection = true
} }
//...增加其他数据库
}); });
SugarIocServices.ConfigurationSugar(db => SugarIocServices.ConfigurationSugar(db =>
{ {
//db0数据过滤
FilterData(0); FilterData(0);
//FilterData(1);
#region db0 #region db0
db.GetConnection(0).Aop.OnLogExecuting = (sql, pars) => db.GetConnectionScope(0).Aop.OnLogExecuting = (sql, pars) =>
{ {
var param = db.GetConnection(0).Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)); var param = db.GetConnectionScope(0).Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value));
logger.Info($"【sql语句】{sql}{param}\n"); logger.Info($"【sql语句】{sql}{param}\n");
}; };
db.GetConnection(0).Aop.OnError = (e) => db.GetConnectionScope(0).Aop.OnError = (e) =>
{ {
logger.Error(e, $"执行SQL出错{e.Message}"); logger.Error(e, $"执行SQL出错{e.Message}");
}; };
//SQL执行完 //SQL执行完
db.GetConnection(0).Aop.OnLogExecuted = (sql, pars) => db.GetConnectionScope(0).Aop.OnLogExecuted = (sql, pars) =>
{ {
//执行完了可以输出SQL执行时间 (OnLogExecutedDelegate) //执行完了可以输出SQL执行时间 (OnLogExecutedDelegate)
}; };
@ -86,7 +86,7 @@ namespace ZR.Admin.WebApi.Extensions
} }
/// <summary> /// <summary>
/// 分页获取count 不会追加sql /// 数据过滤
/// </summary> /// </summary>
/// <param name="configId">多库id</param> /// <param name="configId">多库id</param>
private static void FilterData(int configId) private static void FilterData(int configId)
@ -98,7 +98,7 @@ namespace ZR.Admin.WebApi.Extensions
if (user == null) return; if (user == null) return;
//管理员不过滤 //管理员不过滤
if (user.RoleIds.Any(f => f.Equals("admin"))) return; if (user.RoleIds.Any(f => f.Equals("admin"))) return;
var db = DbScoped.SugarScope.GetConnection(configId); var db = DbScoped.SugarScope.GetConnectionScope(configId);
foreach (var role in user.Roles.OrderBy(f => f.DataScope)) foreach (var role in user.Roles.OrderBy(f => f.DataScope))
{ {
string dataScope = role.DataScope; string dataScope = role.DataScope;

View File

@ -7,21 +7,18 @@
} }
}, },
"ConnectionStrings": { "ConnectionStrings": {
"conn_zrAdmin": "server=LAPTOP-STKF2M8H\\SQLEXPRESS;uid=sa;pwd=zradmin123;database=ZrAdmin;Trusted_Connection=SSPI", "conn_db": "server=LAPTOP-STKF2M8H\\SQLEXPRESS;uid=sa;pwd=zradmin123;database=ZrAdmin;Trusted_Connection=SSPI"
"conn_bus": "server=LAPTOP-STKF2M8H\\SQLEXPRESS;uid=zr;pwd=zradmin123;database=ZrAdmin;Trusted_Connection=SSPI"
}, },
"conn_zrAdmin_type": 1, //MySql = 0, SqlServer = 1 "conn_db_dbtype": 1, // MySql = 0, SqlServer = 1
"conn_bus_type": 1,
"urls": "http://localhost:8888", //urldevServer "urls": "http://localhost:8888", //urldevServer
"corsUrls": "http://localhost:8887", //"," "corsUrls": "http://localhost:8887", //","
"JwtSettings": { "JwtSettings": {
"Issuer": "ZRAdmin.NET", "Issuer": "ZRAdmin.NET",
"Audience": "ZRAdmin.NET", "Audience": "ZRAdmin.NET",
"SecretKey": "SecretKey-ZRADMIN.NET-20210101", "SecretKey": "SecretKey-ZRADMIN.NET-20210101",
"Expire": 30//jwt "Expire": 1440 //jwt
}, },
"DemoMode": false, // "DemoMode": false, //
"DbKey": "", //key
"Upload": { "Upload": {
"UploadUrl": "http://localhost:8888" "UploadUrl": "http://localhost:8888"
}, },

View File

@ -4,6 +4,7 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Data; using System.Data;
using System.Linq.Expressions; using System.Linq.Expressions;
using System.Reflection;
using ZR.Model; using ZR.Model;
namespace ZR.Repository namespace ZR.Repository
@ -18,22 +19,17 @@ namespace ZR.Repository
public BaseRepository(ISqlSugarClient context = null) : base(context) public BaseRepository(ISqlSugarClient context = null) : base(context)
{ {
//通过特性拿到ConfigId //通过特性拿到ConfigId
//var configId = typeof(T).GetCustomAttribute<TenantAttribute>()?.configId; var configId = typeof(T).GetCustomAttribute<TenantAttribute>()?.configId;
//if (configId != null) if (configId != null)
//{
// itenant = DbScoped.SugarScope;//设置租户接口
// Context = DbScoped.SugarScope.GetConnection(configId);
//}
//else
//{
// Context = context ?? DbScoped.SugarScope.GetConnection(1);//根据类传入的ConfigId自动选择
//}
Context = DbScoped.SugarScope.GetConnectionWithAttr<T>();
itenant = DbScoped.SugarScope;//设置租户接口
if (Context == null)
{ {
Context = DbScoped.SugarScope.GetConnection(1);//根据类传入的ConfigId自动选择 Context = DbScoped.SugarScope.GetConnectionScope(configId);//根据类传入的ConfigId自动选择
} }
else
{
Context = context ?? DbScoped.SugarScope.GetConnectionScope(0);//没有默认db0
}
//Context = DbScoped.SugarScope.GetConnectionScopeWithAttr<T>();
itenant = DbScoped.SugarScope;//设置租户接口
} }
#region add #region add