Comments (4)
根据 SqlSugar 官方文档简单修改
-
添加 BaseDbContext 基类
-
添加 DbSet 数据集类
-
添加 SugarDbOptions 配置类
-
根据项目需要,添加 DbContext01,DbContext02,...,继承于 BaseDbContext
-
添加扩展方法 ServiceCollectionExtensions.AddSugarDbContext
-
在 ConfigureServices 添加 DbContext 服务注入 ConfigureServices
具体代码如下
// 1. 添加 BaseDbContext 基类
namespace DbContext
{
public class BaseDbContext
{
private readonly ILogger<BaseDbContext> _logger;
public BaseDbContext(IOptionsSnapshot<SugarDbOptions> namedOptionsAccessor,
ILoggerFactory loggerFactory
)
{
_logger = loggerFactory.CreateLogger<BaseDbContext>();
var options = namedOptionsAccessor.Get(this.GetType().Name);
string connectionString = options.ConnectionString;
string dbType = options.DbType;
Db = new SqlSugarClient(new ConnectionConfig()
{
ConnectionString = connectionString,
DbType = (DbType)Enum.Parse(typeof(DbType), dbType),//DbType.SqlServer,
InitKeyType = InitKeyType.Attribute,//从特性读取主键和自增列信息
IsAutoCloseConnection = true,//开启自动释放模式和EF原理一样我就不多解释了
});
//调式代码 用来打印SQL
Db.Aop.OnLogExecuting = (sql, pars) =>
{
_logger.LogInformation(sql + "\r\n" +
Db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)));
};
}
public BaseDbContext(string connectionString, string dbType)
{
this.GetType();
Db = new SqlSugarClient(new ConnectionConfig()
{
ConnectionString = connectionString,
DbType = (DbType)Enum.Parse(typeof(DbType), dbType),//DbType.SqlServer,
InitKeyType = InitKeyType.Attribute,//从特性读取主键和自增列信息
IsAutoCloseConnection = true,//开启自动释放模式和EF原理一样我就不多解释了
});
//调式代码 用来打印SQL
Db.Aop.OnLogExecuting = (sql, pars) =>
{
_logger.LogInformation(sql + "\r\n" +
Db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)));
};
}
//注意:不能写成静态的
public SqlSugarClient Db;//用来处理事务多表查询和复杂的操作
}
}
// 2. 添加 DbSet 数据集类
namespace DbContext
{
//可以直接用SimpleClient也可以扩展一个自个的类
//推荐直接用 SimpleClient
//为了照顾需要扩展的朋友,我们就来扩展一个SimpleClient,取名叫DbSet
public class DbSet<T> : SimpleClient<T> where T : class, new()
{
public DbSet(SqlSugarClient context) : base(context)
{
}
//SimpleClient中的方法满足不了你,你可以扩展自已的方法
public List<T> GetByIds(dynamic[] ids)
{
return Context.Queryable<T>().In(ids).ToList(); ;
}
}
}
// 3. 添加 SugarDbOptions 配置类
namespace DbContext
{
public class SugarDbOptions
{
public string ConnectionString { get; set; } //连接字符串
public string DbType { get; set; } //数据库类型
}
}
// 4. 根据项目需要,添加 DbContext01,DbContext02,...,继承于 BaseDbContext
namespace DbContext
{
public class DbContext01 : BaseDbContext
{
public DbContext01(IOptionsSnapshot<SugarDbOptions> namedOptionsAccessor,ILoggerFactory loggerFactory):base(namedOptionsAccessor, loggerFactory){}
// DbSet数据表
public DbSet<表1> 表1 { get { return new DbSet<表1>(Db); } }
public DbSet<表2> 表2 { get { return new DbSet<表2>(Db); } }
public DbSet<表3> 表3 { get { return new DbSet<表3>(Db); } }
}
}
// 5. 添加扩展方法 ServiceCollectionExtensions.AddSugarDbContext
namespace Extensions
{
public static IServiceCollection AddSugarDbContext<T>(this IServiceCollection services, Action<SugarDbOptions> setupAction) where T : class
{
services.AddScoped<T>();
string name = typeof(T).Name;
var options = services.AddOptions<SugarDbOptions>(name);
services.Configure<SugarDbOptions>(name, setupAction);
return services;
}
}
}
// 6. 在 ConfigureServices 添加 DbContext 服务注入 ConfigureServices
services.AddSugarDbContext<DbContext01>(options =>
{
options.ConnectionString = Configuration["DbContext:DbContext01:ConnectionString"];
options.DbType = Configuration["DbContext:DbContext01:DbType"];
});
//对应配置文件
"DbContext": {
"DbContext01": {
"Enabled": true,
"ConnectionString": "Server=.;Database=Db01;User ID=sa;Password=123;",
"DbType": "SqlServer"
}
}
- 后续问题
这个方法能解决按不同业务模块分库的问题.对于水平分库扩展还有改进的空间.
比如项目初期10万用户以内只有一个库,每增加10万用户自动增加一个库.
或者多租户系统,每个增加租户添加一个库.
需要根据不同的库动态切换连接字符串.
暂时还没有想到解决方案....
from blog.core.
你这个是配置多个上下文,每个上下文对应一个db库,如果使用的话,再去切换吧。
他问是好像是同时操作两个db,就是你说的,A租户过来自动使用A数据库连接字符串,B操作B。
from blog.core.
services.AddScoped(provider =>
{
Func<string, SqlSugarClient> func = key =>
{
switch (key)
{
case "1":
return new SqlSugarClient(new ConnectionConfig()
{
ConnectionString = sqlSugarConfig.Item2,
DbType = sqlSugarConfig.Item1,
IsAutoCloseConnection = true,
InitKeyType = InitKeyType.Attribute,
});
case "2":
return new SqlSugarClient(new ConnectionConfig()
{
ConnectionString = sqlSugarConfig.Item2,
DbType = sqlSugarConfig.Item1,
IsAutoCloseConnection = true,
InitKeyType = InitKeyType.Attribute,
});
default:
throw new NotSupportedException($"Not Support key : {key}");
}
};
return func;
});
private readonly Func<string, SqlSugarClient> _serviceAccessor;
public HomeController( Func<string, SqlSugarClient> serviceAccessor
)
{
_serviceAccessor=serviceAccessor;
}
获取方式 var db =_serviceAccessor("1")
这是另外一个大佬提供的方案,可以学习一下
from blog.core.
我这边实现了多库操作,但是不是多个上下文的。
#46
from blog.core.
Related Issues (20)
- 334issue的打包报错问题解决了,但是还是没有生成Blog.Core.dll文件 HOT 1
- 无法安装Blog.Core.Webapi.Template,下载失败 HOT 1
- BaseRepository的类增加了其他Model的调用方法,方便不同库的操作。
- 加了一个ModelMapHelper类 HOT 1
- 开发阶段swagger自动填充token HOT 1
- 选择sql server 数据库初始化数据时,数据库存储中文时都是"??????"这种符号 HOT 1
- master版本 源码上有段Null转换的代码注释了,导致在模型绑定解析阶段有字段为null时出现解析错误。 HOT 2
- 配置中心的使用流程问题 HOT 4
- 实现SqlSugar的ICacheService接口内的GetAllKey发生空对象错误 HOT 3
- delete怎么按照sql语句删除呢 HOT 1
- 更新到net8版本 HOT 2
- apk.neters.club 网站打不开了
- 最新版生成多sql条件时语句不正确 HOT 2
- 开源很不错,这个代码对新手很友好 HOT 2
- 当我使用UseTran在调用基类方法的时候 会出现锁库的情况。 HOT 5
- 当我用docker 启动多个实例后,登录到swagger,调用不同实例的接口后会抛出以下警告 HOT 2
- var cacheOptions = App.GetOptions<RedisOptions>(); null HOT 2
- 杭州
- 事务锁表问题 HOT 1
- CreateYourProject.bat 如何创建.net8 版本的项目
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from blog.core.