.net 5.0 + sqlsugarcore(5.0.4.2)
一、SqlSugarScope 、SqlSugarClient 、SqlConnection区别
一、区别
scope是对client的进一步封装,为了支持线程安全,并且在不同上下文中自动new出一个client,在编写代码时不需要考虑他线程是否安全
二、总结
他们3者的关系应该是这样的:
| SqlSugarScope 底层+自动释放+上下文安全 |
| SqlSugarClient 底层+自动释放控制 |
| SqlConnection 底层 |
三、引申
1.什么是上下文?
| 异步情况: 在同一串await 中是一个上下文 |
| 同步情况: 在同一个线程是同一个上下文 |
| 同一个SqlSugarScope做到了在同一个上下文共享一个对象,不同上下文自动去NEW |
二、Code First、DB First
一、code first
1.创建方式
| |
| |
| |
| public static void CodeFirstShow() |
| { |
| ConnectionConfig config = new ConnectionConfig() |
| { |
| ConnectionString = "", |
| DbType = DbType.SqlServer, |
| IsAutoCloseConnection = true, |
| }; |
| |
| using (SqlSugarClient db = new SqlSugarClient(config)) |
| { |
| |
| db.DbMaintenance.CreateDatabase(); |
| Type[] types = Assembly |
| .LoadFrom("类库") |
| .GetTypes() |
| .ToArray(); |
| |
| db.CodeFirst.SetStringDefaultLength(200).InitTables(types); |
| } |
| } |
2.code first 上下文创建数据库
| public class SugarDbContext |
| { |
| public SqlSugarClient Db; |
| public SugarDbContext() |
| { |
| |
| Db = new SqlSugarClient(new ConnectionConfig() |
| { |
| ConnectionString = "server=.;database=StudentDb;uid=cnpy;pwd=cnpy1314;", |
| DbType = DbType.SqlServer, |
| IsAutoCloseConnection = true, |
| InitKeyType = InitKeyType.Attribute |
| }); |
| |
| |
| Db.Aop.OnLogExecuting = (sql, pars) => |
| { |
| Console.WriteLine(sql + "\r\n" + Db.Utilities.SerializeObject |
| (pars.ToDictionary(it => it.ParameterName, it => it.Value))); |
| Console.WriteLine(); |
| }; |
| } |
| public void CreateTable(bool Backup = false, int StringDefaultLength = 50, params Type[] types) |
| { |
| Db.CodeFirst.SetStringDefaultLength(StringDefaultLength); |
| Db.DbMaintenance.CreateDatabase(); |
| |
| if (Backup) |
| { |
| Db.CodeFirst.BackupTable().InitTables(types); |
| } |
| else |
| { |
| Db.CodeFirst.InitTables(types); |
| } |
| } |
| |
| public SimpleClient<Students> studentDb { get { return new SimpleClient<Students>(Db); } } |
| public SimpleClient<Schools> schoolDb { get { return new SimpleClient<Schools>(Db); } } |
| |
| } |
二、DB First
1.创建方式
| |
| |
| |
| |
| public static void DbFirstShow() { |
| ConnectionConfig config = new ConnectionConfig() { |
| ConnectionString="", |
| DbType=DbType.SqlServer, |
| IsAutoCloseConnection=true, |
| }; |
| using (SqlSugarClient db=new SqlSugarClient(config)) |
| { |
| |
| |
| db.DbFirst |
| .IsCreateAttribute() |
| .CreateClassFile("类库所在文件夹","类库名称"); |
| } |
| } |
![1665629478403]()
数据表
! 联表查询
联表查询:
| |
| SqlSugarClient Db = new SqlSugarClient(new ConnectionConfig() { |
| ConnectionString = "Data Source=.;Initial Catalog=CoreShop;User ID=sa;Password=sa123;", |
| DbType = DbType.SqlServer, |
| IsAutoCloseConnection = true |
| }); |
| |
| Db.Aop.OnLogExecuting = (sql, pars) => |
| { |
| Console.WriteLine(sql); |
| |
| |
| |
| }; |
| |
| var cart = Db.Queryable<CoreCmsCart>().ToList(); |
| |
| |
| |
| var goods= Db.Queryable<CoreCmsProducts, CoreCmsGoods, CoreCmsCart>((o, i, c) => new JoinQueryInfos( |
| JoinType.Left, o.goodsId == i.id, |
| JoinType.Left, o.id == c.productId)) |
| .Select((o, i, c) => new { name=i.name, price = o.price }) |
| .ToList(); |
| |
| |
| var view = new object (); |
| |
| var items = _coreCmsGoodsServices.QueryMuch<CoreCmsProducts, CoreCmsGoods, CoreCmsCart, GoodsDetailsVM>( |
| (p, g, c) => new object[] { JoinType.Left, p.goodsId == g.id, JoinType.Left, p.id == c.productId }, |
| (p, g, c) => new GoodsDetailsVM { Id = c.id, name = g.name, price = p.price } |
| ); |
| |
| |
| |
三、项目使用
1、启动sqlsugar服务
| |
| |
| |
| public static class SqlSugarSetup |
| { |
| |
| public static void AddSqlSugarSetup(this IServiceCollection services) |
| { |
| if (services == null) throw new ArgumentNullException(nameof(services)); |
| |
| |
| SugarIocServices.AddSqlSugar(new IocConfig() |
| { |
| |
| ConnectionString = AppSettingsConstVars.DbSqlConnection, |
| |
| DbType = AppSettingsConstVars.DbDbType == IocDbType.MySql.ToString() ? IocDbType.MySql : IocDbType.SqlServer, |
| |
| IsAutoCloseConnection = true, |
| }); |
| |
| |
| services.ConfigurationSugar(db => |
| { |
| db.CurrentConnectionConfig.InitKeyType = InitKeyType.Attribute; |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| db.Aop.OnError = (exp) => |
| { |
| |
| NLogUtil.WriteFileLog(NLog.LogLevel.Error, LogType.Other, "SqlSugar", "执行SQL错误事件", exp); |
| }; |
| |
| |
| |
| |
| |
| }); |
| |
| } |
| } |
2、注入服务
| |
| services.AddSqlSugarSetup(); |
3.创建工作单元接口、实现 UnitOfWork
| using SqlSugar; |
| |
| public interface IUnitOfWork |
| { |
| SqlSugarScope GetDbClient(); |
| void BeginTran(); |
| void CommitTran(); |
| void RollbackTran(); |
| } |
| |
点击查看代码
| public class UnitOfWork : IUnitOfWork |
| { |
| private readonly ISqlSugarClient _sqlSugarClient; |
| |
| |
| public UnitOfWork() |
| { |
| _sqlSugarClient = DbScoped.SugarScope; |
| } |
| |
| |
| |
| |
| |
| public SqlSugarScope GetDbClient() |
| { |
| |
| return _sqlSugarClient as SqlSugarScope; |
| } |
| |
| public void BeginTran() |
| { |
| GetDbClient().BeginTran(); |
| } |
| |
| public void CommitTran() |
| { |
| try |
| { |
| GetDbClient().CommitTran(); |
| } |
| catch (Exception ex) |
| { |
| GetDbClient().RollbackTran(); |
| NLogUtil.WriteFileLog(LogLevel.Error, LogType.Web, "事务提交异常", "事务提交异常", new Exception("事务提交异常", ex)); |
| throw; |
| } |
| } |
| |
| public void RollbackTran() |
| { |
| GetDbClient().RollbackTran(); |
| } |
| } |
| |
4、使用
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?