1.//首先引入SqlSugarCore包
2.//新建SqlsugarSetup类
public static class SqlsugarSetup
{
public static void AddSqlsugarSetup(this IServiceCollection services, IConfiguration configuration,
string dbName = "ConnectString")
{
SqlSugarScope sqlSugar = new SqlSugarScope(new ConnectionConfig()
{
//如果是mysql,换成SqlSugar.DbType.MySql
DbType = SqlSugar.DbType.SqlServer,
ConnectionString = configuration[dbName],
IsAutoCloseConnection = true,
},
db =>
{
//单例参数配置,所有上下文生效
db.Aop.OnLogExecuting = (sql, pars) =>
{
Console.WriteLine(sql);//输出sql
};
});
services.AddSingleton<ISqlSugarClient>(sqlSugar);//这边是SqlSugarScope用AddSingleton
}
}
3.//在appsettings添加连接字符串
"ConnectString": "Server=.;Database=db;User=sa;Password=123456;"
4.//在Program注入SqlsugarSetup类
builder.Services.AddSqlsugarSetup(builder.Configuration);
5.//在方法中依赖注入文章来源:https://www.toymoban.com/news/detail-639235.html
private readonly ISqlSugarClient _SqlSugarDB;
/// <summary>
/// 依赖注入
/// </summary>
public AnsweringQuestionService(ISqlSugarClient SqlSugarDB)
{
_SqlSugarDB = SqlSugarDB;
}
6.使用SqlSugar增删改查文章来源地址https://www.toymoban.com/news/detail-639235.html
//查询
var a = _SqlSugarDB.Queryable<UserInfo>().ToList();
var b = _SqlSugarDB.Queryable<UserInfo>().Where(a => a.UserID == "1").ToList();
//插入
var res =_SqlSugarDB.Insertable<UserInfo>(new UserInfo() { UserName = "LiuHG", Password = "123456", Role = 1 }).ExecuteCommand();
//更新
var res =_SqlSugarDB.Updateable(new UserInfo() { Id = 1, UserName = "lhg", Role = 2, Password = "123456" }).ExecuteCommand();
//删除
var res =_SqlSugarDB.Deleteable<UserInfo>().Where(it => it.Id == 1).ExecuteCommand();
到了这里,关于.NET6使用SqlSugar操作数据库的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!