1、Nuget先引入:SqlSugarCore
2、注入ISqlSugarClient
先封装一个操作类
//建一个扩展类
public static class SqlsugarSetup
{
public static void AddSqlsugarSetup(this IServiceCollection services, IConfiguration configuration,
string dbName = "db_master")
{
SqlSugarScope sqlSugar = new SqlSugarScope(new ConnectionConfig()
{
DbType = SqlSugar.DbType.SqlServer,
ConnectionString = configuration.GetConnectionString(dbName),
IsAutoCloseConnection = true,
},
db =>
{
//单例参数配置,所有上下文生效
db.Aop.OnLogExecuting = (sql, pars) =>
{
//Console.WriteLine(sql);//输出sql
};
//技巧:拿到非ORM注入对象
//services.GetService<注入对象>();
});
services.AddSingleton<ISqlSugarClient>(sqlSugar);//这边是SqlSugarScope用AddSingleton
}
}
//Startup.cs或者Program 文件添加下面代码
//services.AddSqlsugarSetup(Configuration);
Program.cs中的配置
builder.Services.AddSqlsugarSetup(builder.Configuration, "db_master");
这里的db_master如果有默认值可以不写。
{mtitle}注意的地方:{/mtitle}
appsettings.json 文件中一定要加 ConnectionStrings 包一下,否则会报数据库链接字符串错误。
"ConnectionStrings": {
"db_master": "Data Source=.;Initial Catalog=WApp;Persist Security Info=True;User ID=sa;Password=123456"
}
3、新建一个Controller 来测试一下
[Route("api/[controller]/[action]")]
[ApiController]
public class DbTstController : ControllerBase
{
private readonly ISqlSugarClient _db;
public DbTstController(ISqlSugarClient db)
{
this._db = db;
}
[HttpGet]
public List<SysUser> GetSysUserList()
{
List<SysUser> lst = _db.Queryable<SysUser>().ToList();
return lst;
}
}
OK啦
补充一个非WEBAPI程序引用sqlsuger
/*-------------------------------------------------------------------------
* 命名空间名称/文件名: jycurrent.Common/SqlHelper
* CLR版本: 4.0.30319.42000
* 机器名称: RGDQ001
* 功 能: N/A
* 类 名: SqlHelper
* 创建时间: 2023/7/24 14:39:50
* 版本号: v1.0
* 创建人: C'est la vie
*-------------------------------------------------------------------------*/
using SqlSugar;
namespace jycurrent.Common
{
internal class SqlHelper
{
public static SqlSugarClient db
{
get => new SqlSugarClient(new ConnectionConfig()
{
ConnectionString = "server=localhost;port=3306;database=hl_2023;user=root;password=rgdq2019##;Charset=utf8;SslMode=none;Allow User Variables=True;",
DbType = DbType.MySql,
IsAutoCloseConnection = true
},
db => {
//5.1.3.24统一了语法和SqlSugarScope一样,老版本AOP可以写外面
db.Aop.OnLogExecuting = (sql, pars) =>
{
//Console.WriteLine(sql);//输出sql,查看执行sql 性能无影响
};
});
}
}
}
在需要使用的地方 SqlHelper.db.Queryable<SysUser>().ToList();
就是这么简单
评论 (0)