在使用 **SqlSugar** 进行分库操作时,可以通过配置多个数据库连接,并根据业务逻辑动态切换数据库。以下是一个完整的分库示例,展示如何实现分库功能。
---
### **1. 安装 NuGet 包**
安装 `SqlSugarCore`:
```bash
dotnet add package SqlSugarCore
```
---
### **2. 分库场景**
假设有两个数据库:
- **主库**:用于写操作。
- **从库**:用于读操作。
---
### **3. 配置数据库连接**
在 `appsettings.json` 中配置多个数据库连接:
```json
{
"ConnectionStrings": {
"Master": "Server=master_server;Database=master_db;User Id=your_user;Password=your_password;",
"Slave": "Server=slave_server;Database=slave_db;User Id=your_user;Password=your_password;"
}
}
```
---
### **4. 创建数据库上下文**
创建一个 `SqlSugarContext` 类,用于管理主库和从库的连接。
```csharp
using Microsoft.Extensions.Configuration;
using SqlSugar;
public class SqlSugarContext
{
private readonly IConfiguration _configuration;
private readonly SqlSugarClient _masterDb;
private readonly SqlSugarClient _slaveDb;
public SqlSugarContext(IConfiguration configuration)
{
_configuration = configuration;
// 初始化主库
_masterDb = new SqlSugarClient(new ConnectionConfig
{
ConnectionString = _configuration["ConnectionStrings:Master"],
DbType = DbType.SqlServer,
IsAutoCloseConnection = true,
InitKeyType = InitKeyType.Attribute
});
// 初始化从库
_slaveDb = new SqlSugarClient(new ConnectionConfig
{
ConnectionString = _configuration["ConnectionStrings:Slave"],
DbType = DbType.SqlServer,
IsAutoCloseConnection = true,
InitKeyType = InitKeyType.Attribute
});
}
// 获取主库
public SqlSugarClient MasterDb => _masterDb;
// 获取从库
public SqlSugarClient SlaveDb => _slaveDb;
}
```
---
### **5. 使用分库**
在业务逻辑中,根据需要切换主库和从库。
#### **5.1 写入主库**
```csharp
public class UserService
{
private readonly SqlSugarContext _dbContext;
public UserService(SqlSugarContext dbContext)
{
_dbContext = dbContext;
}
public async Task AddUserAsync(User user)
{
await _dbContext.MasterDb.Insertable(user).ExecuteCommandAsync();
}
}
```
#### **5.2 读取从库**
```csharp
public class UserService
{
private readonly SqlSugarContext _dbContext;
public UserService(SqlSugarContext dbContext)
{
_dbContext = dbContext;
}
public async Task<List<User>> GetUsersAsync()
{
return await _dbContext.SlaveDb.Queryable<User>().ToListAsync();
}
}
```
---
### **6. 主程序**
在 `Program.cs` 中初始化 `SqlSugarContext` 并使用分库功能。
```csharp
using Microsoft.Extensions.Configuration;
using System.IO;
using System.Threading.Tasks;
public class Program
{
public static async Task Main(string[] args)
{
// 读取配置文件
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.Build();
// 初始化数据库上下文
var dbContext = new SqlSugarContext(configuration);
// 使用主库写入数据
var userService = new UserService(dbContext);
await userService.AddUserAsync(new User { Name = "John", Age = 30 });
// 使用从库读取数据
var users = await userService.GetUsersAsync();
foreach (var user in users)
{
Console.WriteLine($"User: {user.Name}, Age: {user.Age}");
}
}
}
```
---
### **7. 动态分库**
如果需要根据条件动态切换数据库,可以在 `SqlSugarContext` 中添加一个方法,根据条件返回对应的数据库连接。
#### **7.1 修改 `SqlSugarContext`**
```csharp
public SqlSugarClient GetDb(bool isWriteOperation)
{
return isWriteOperation ? _masterDb : _slaveDb;
}
```
#### **7.2 使用动态分库**
```csharp
public class UserService
{
private readonly SqlSugarContext _dbContext;
public UserService(SqlSugarContext dbContext)
{
_dbContext = dbContext;
}
public async Task AddUserAsync(User user)
{
var db = _dbContext.GetDb(isWriteOperation: true); // 使用主库
await db.Insertable(user).ExecuteCommandAsync();
}
public async Task<List<User>> GetUsersAsync()
{
var db = _dbContext.GetDb(isWriteOperation: false); // 使用从库
return await db.Queryable<User>().ToListAsync();
}
}
```
---
### **8. 总结**
通过以上步骤,您可以实现基于 SqlSugar 的分库功能:
1. 配置多个数据库连接。
2. 使用 `SqlSugarContext` 管理主库和从库。
3. 在业务逻辑中根据需要切换数据库。
这种分库方式适用于读写分离、多租户等场景,能够有效提升系统的性能和扩展性。