Dapper笔记-Dapper.Extensions
介绍
1.支持 MySQL、SQL Server、PostgreSQL、SQLite 和 ODBC。
2.支持缓存。
3.支持sql分离。
4.支持读写分离。
5.支持性能监控。
相关Nuget包
Dapper.Extensions
Dapper.Extensions.NetCore
Dapper.Extensions.MySQL
Dapper.Extensions.MSSQL
Dapper.Extensions.PostgreSQL
Dapper.Extensions.ODBC
Dapper.Extensions.SQLite
Dapper.Extensions.Caching.Redis
Dapper.Extensions.Caching.Memory
Dapper.Extensions.MiniProfiler
开始
1、安装nuget
<ItemGroup>
<PackageReference Include="Dapper.Contrib" Version="2.0.78" />
<PackageReference Include="Dapper.Extensions.MySQL" Version="4.0.5" />
</ItemGroup>
2、添加配置
{
"ConnectionStrings": {
"DefaultConnection": "Server=***;Port=3306;Database=dapper.master; User=root;Password=123;",
"mysql_master_slave": {
"Master": "Server=***;Port=3306;Database=dapper.master; User=root;Password=123;",
"Slaves": [
{
"ConnectionString": "Server=***;Port=3306;Database=dapper.slave1; User=root;Password=123;",
"Weight": 4
},
{
"ConnectionString": "Server=***;Port=3306;Database=dapper.slave1; User=root;Password=123;",
"Weight": 6
}
]
}
}
}
3、program添加
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews().AddControllersAsServices(); ;
//替换内置的ServiceProviderFactory
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
builder.Host.ConfigureContainer<ContainerBuilder>(containerBuilder =>
{
containerBuilder.AddDapperForMySQL();
containerBuilder.AddDapperForMySQL("mysql_master_slave", "mysql_master_slave", true);
containerBuilder.AddAllControllers();
});
4、controller
public class HomeController : Controller
{
private readonly IDapper defaultDapper;
private readonly IDapper masterDapper;
private readonly IDapper slaveDapper;
public HomeController(
IDapper defaultDapper, //DefaultConnection
[DependencyDapper("mysql_master_slave")] IDapper masterDapper,
[DependencyDapper("mysql_master_slave", true)] IDapper slaveDapper)
{
this.defaultDapper = defaultDapper;
this.masterDapper = masterDapper;
this.slaveDapper = slaveDapper;
var defaultConnStr = defaultDapper.Conn.Value.ConnectionString;
var masterConnStr = masterDapper.Conn.Value.ConnectionString;
var slaveConnStr = slaveDapper.Conn.Value.ConnectionString;
}
//使用DefaultConnection
public async Task<IActionResult> Index()
{
//Insert方式使用Dapper.Contrib包
long id = defaultDapper.Conn.Value.Insert(new UserInfo { Name = "fan1", Age = 10, Birthday = DateTime.Now, CreateTime = DateTime.Now });
List<UserInfo> userInfoList = await defaultDapper.QueryAsync<UserInfo>("select * from UserInfo");
return View();
}
//主从
public async Task<IActionResult> Index1()
{
List<UserInfo> userInfoList1 = await masterDapper.QueryAsync<UserInfo>("select * from UserInfo");
List<UserInfo> userInfoList2 = await slaveDapper.QueryAsync<UserInfo>("select * from UserInfo");
return View();
}
}