SQLSugar入门篇:快速上手与基础概念


前言

    SqlSugar 是一款 老牌 .NET开源ORM框架,由果糖大数据科技团队维护和更新 ,开箱即用最易上手的ORM 。


一、框架简介

     SqlSugar 是一款 老牌 .NET开源ORM框架,由果糖大数据科技团队维护和更新 ,开箱即用最易上手的ORM

优点 :【生态丰富】【高性能】【超简单】 【功能全面】 【多库兼容】【适合产品】 【SqlSugar视频教程】
支持 :.net framework .net core3.1 .ne5 .net6 .net7 .net8 .net9
特色 :拥有全球最活跃的ORM线上论坛,比EF还要活跃,交流群人数已超过万人 ,技术支持快,口碑好。
开源 :10年开源信誉值得信赖,从不搞收费,文档也全免费(MIT开源协议)

数据库支持:
     EF Core的数据库驱动是不同公司开发,函数、建表标准不统一后期换库成本比较高
     SqlSugar花了8年多时间完善中间标准真正的多库ORM,只需要改一下DbType就完成了切换数据库
在这里插入图片描述

二、环境搭建与安装

1.net core和.net5/.net6/.net7/.net8/.net9环境

     安装SqlSugarCore
在这里插入图片描述
     安装完就可以写代码了

2.net framework4.6+ 环境

     安装SqlSugar

在这里插入图片描述

     安装完就可以写代码了

三、环境搭建与安装

1.对象说明

    我们可以通过SqlSugarClient 或者SqlSugarScope 来操作数据库 ,API都一样只是模式不同

  • SqlSugarClient 原生模式访问数据库
  • SqlSugarScope 单例模式访问数据库
    在这里插入图片描述

2.原生模式:SqlSugarClient

    SqlSugarClient 每次请求new一个新对象,db禁止跨上下文使用,IOC建议用Scope或者瞬发注入

using SqlSugar;
 
 
//创建数据库对象 (用法和EF Dappper一样通过new保证线程安全)
SqlSugarClient Db = new SqlSugarClient(new ConnectionConfig()
{
    ConnectionString = "datasource=demo.db",
    DbType = DbType.Sqlite,
    IsAutoCloseConnection = true
},
db => {
  
        db.Aop.OnLogExecuting = (sql, pars) =>
        {
             
            //获取原生SQL推荐 5.1.4.63  性能OK
            Console.WriteLine(UtilMethods.GetNativeSql(sql, pars));
 
            //获取无参数化SQL 对性能有影响,特别大的SQL参数多的,调试使用
            //Console.WriteLine(UtilMethods.GetSqlString(DbType.SqlServer,sql,pars))
 
 
         };
 
        //注意多租户 有几个设置几个
        //db.GetConnection(i).Aop
 
    });
 
//建库
Db.DbMaintenance.CreateDatabase();//达梦和Oracle不支持建库
 
//建表(看文档迁移)
Db.CodeFirst.InitTables<Student>(); //所有库都支持     
 
//查询表的所有
var list = Db.Queryable<Student>().ToList();
 
//插入
Db.Insertable(new Student() { SchoolId = 1, Name = "jack" }).ExecuteCommand();
 
//更新
Db.Updateable(new Student() { Id = 1, SchoolId = 2, Name = "jack2" }).ExecuteCommand();
 
//删除
Db.Deleteable<Student>().Where(it => it.Id == 1).ExecuteCommand();
  
 
 
//实体与数据库结构一样
public class Student
{
    //数据是自增需要加上IsIdentity 
    //数据库是主键需要加上IsPrimaryKey 
    //注意:要完全和数据库一致2个属性
    [SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
    public int Id { get; set; }
    public int? SchoolId { get; set; }
    public string? Name { get; set; }
}

    原生模式使用IOC:

    Scope我们需要用SqlSugarClient

//注册上下文:AOP里面可以获取IOC对象,如果有现成框架比如Furion可以不写这一行
services.AddHttpContextAccessor();
//注册SqlSugar用AddScoped
services.AddScoped<ISqlSugarClient>(s =>
{
    //Scoped用SqlSugarClient 
    SqlSugarClient sqlSugar = new SqlSugarClient (new ConnectionConfig()
    {
        DbType = SqlSugar.DbType.Sqlite,
        ConnectionString = "DataSource=sqlsugar-dev.db",
        IsAutoCloseConnection = true,
    },
   db =>
   {
      //每次上下文都会执行
            
      //获取IOC对象不要求在一个上下文
      //var log=s.GetService<Log>()
                
      //获取IOC对象要求在一个上下文
      //var appServive = s.GetService<IHttpContextAccessor>();
      //var log= appServive?.HttpContext?.RequestServices.GetService<Log>();
                 
       db.Aop.OnLogExecuting = (sql, pars) =>
       {
        
       };
   });
    return sqlSugar;
});
 
 
//用接口接收
public class(ISqlSugarClient  db)

3.单例模式:SqlSugarScope

     AddSingleton 我们需要用SqlSugarScope单例对象

//注册上下文:AOP里面可以获取IOC对象,如果有现成框架比如Furion可以不写这一行
services.AddHttpContextAccessor();
//注册SqlSugar
services.AddSingleton<ISqlSugarClient>(s =>
{
    SqlSugarScope sqlSugar = new SqlSugarScope(new ConnectionConfig()
    {
        DbType = SqlSugar.DbType.Sqlite,
        ConnectionString = "DataSource=sqlsugar-dev.db",
        IsAutoCloseConnection = true,
    },
   db =>
   {         
      //每次上下文都会执行
            
      //获取IOC对象不要求在一个上下文
      //var log=s.GetService<Log>()
                
      //获取IOC对象要求在一个上下文
      //var appServive = s.GetService<IHttpContextAccessor>();
      //var log= appServive?.HttpContext?.RequestServices.GetService<Log>();
                 
       db.Aop.OnLogExecuting = (sql, pars) =>
       {
        
       };
   });
    return sqlSugar;
});
 
//用接口接收
public class(ISqlSugarClient  db)

4.多库用法

var db = new SqlSugarClient(new List<ConnectionConfig>()
{
     new ConnectionConfig()
      {
           ConfigId="0",DbType=DbType.SqlServer,ConnectionString=..,IsAutoCloseConnection=true
      },
      
     new ConnectionConfig()
     {
          ConfigId="1",DbType=DbType.MySql,ConnectionString=..,IsAutoCloseConnection=true 
     }
});
var childA=db.GetConnection("A");
var childB=db.GetConnection("B");

5.连接参数

     SqlSugarClient是通过ConnectionConfig进行传参数详细参数如下
在这里插入图片描述

四、实体类映射

1.实体使用自带特性

[SugarTable("dbstudent")]//当和数据库名称不一样可以设置表别名 指定表明
public class Student
{
    [SugarColumn(IsPrimaryKey = true, IsIdentity = true)]//数据库是自增才配自增 
    public int Id { get; set; }
    public int? SchoolId { get; set; }
    [SugarColumn(ColumnName ="StudentName")]//数据库与实体不一样设置列名 
    public string Name { get; set; }
}

2.实体使用自定义特性

SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
{
    ConnectionString = Config.ConnectionString,
    DbType = DbType.SqlServer,
    IsAutoCloseConnection = true,
    ConfigureExternalServices = new ConfigureExternalServices()
    {
        EntityService = (property, column) =>
        {
            var attributes = property.GetCustomAttributes(true);//get all attributes 
 
            if (attributes.Any(it => it is KeyAttribute))// by attribute set primarykey
            {
                column.IsPrimarykey = true; //有哪些特性可以看 1.2 特性明细
            }
            //可以写多个,这边可以断点调试
            // if (attributes.Any(it => it is NotMappedAttribute))
            //{
                //    column.IsIgnore= true; 
             //}
        },
        EntityNameService = (type, entity) =>
        {
            var attributes = type.GetCustomAttributes(true);
            if (attributes.Any(it => it is TableAttribute))
            {
              var attr=(attributes.First(it=>it is TableAttribute) as TableAttribute);
              entity.DbTableName = attr.Name;
            }
        }
    }
});
 
[Table("student")]
//[SugarTable("student")]
public class MyStudent
{
 
    [Key]
    //[SugarColumn(IsPrimaryKey =true)]
    public string Id { get; set; }
    public string Name { get; set; }
}

3.迁移建表

public class CodeFirstTable1
{
        [SugarColumn(IsIdentity = true, IsPrimaryKey = true)]
        public int Id { get; set; } 
        public string Name { get; set; }
        //ColumnDataType 一般用于单个库数据库,如果多库不建议用
        [SugarColumn(ColumnDataType = "Nvarchar(255)")]
        public string Text { get; set; }
        [SugarColumn(IsNullable = true)]//可以为NULL
        public DateTime CreateTime { get; set; }
}
  
//建表
db.CodeFirst.SetStringDefaultLength(200).InitTables(typeof(CodeFirstTable1));

4.生成实体

//.net6以下
db.DbFirst.IsCreateAttribute().CreateClassFile("c:\\Demo\\1", "Models");
  
//.net6以上 string加?
db.DbFirst.IsCreateAttribute().StringNullable().CreateClassFile("c:\\Demo\\1", "Models");

五、基础CRUD操作

1.基础查询

查所有

List<Student> list=db.Queryable<Student>().ToList()
//select * from Student

查询总数

int count=db.Queryable<Student>().Count()
//select count(1) from Student

按条件查询

db.Queryable<Student>().Where(it=>it.Id==1).ToList()
//select * from Student where id=1

2.基础插入

//返回插入行数
db.Insertable(insertObj).ExecuteCommand(); //都是参数化实现
//异步: await db.Insertable(insertObj).ExecuteCommandAsync()
 
//插入返回自增列 (实体除ORACLE外实体要配置自增,Oracle需要配置序列)
db.Insertable(insertObj).ExecuteReturnIdentity();
//异步: await db.Insertable(insertObj).ExecuteReturnIdentityAsync();

3.基础更新

//根据主键更新单条 参数 Class
var result= db.Updateable(updateObj).ExecuteCommand();//实体有多少列更新多少列

4.基础删除

//单个实体
db.Deleteable<Student>(new Student() { Id = 1 }).ExecuteCommand();

六、事务管理

1.单库事务

     单库事务是针一个db操作执行的事务,无论是 ISqlSugarClient和 SqlSugarClient 用法都一样

try
    {
        db.Ado.BeginTran();
        db.Insertable(new Order() { .....}).ExecuteCommand();
        db.Insertable(new Order() { .....}).ExecuteCommand();
        db.Ado.CommitTran();
    }
    catch (Exception ex)
    {
        db.Ado.RollbackTran();
        throw ex;
    }

2.多库事务(可跨库)

    多数据库事务是SqlSugar独有的功能,稳定比CAP更强(CAP还有一层队列),在单个程序中可以很愉快的使用多库事务

     SqlSugarClient或者SqlSugarSope 继承于2个接口 ,代码如下事务

SqlSugarClient : ISqlSugarClient, ITenant

     多租户声明

SqlSugarClient db = new SqlSugarClient(new List<ConnectionConfig>()
{
  new ConnectionConfig()
  { ConfigId="0", DbType=DbType.SqlServer,ConnectionString=..,IsAutoCloseConnection=true},
   
  new ConnectionConfig()
  { ConfigId="1", DbType=DbType.MySql,ConnectionString=..,IsAutoCloseConnection=true}
});

     简单的说多租户事务和单库事务用法基本100%一致,唯一区别就是少了.Ado

db.Ado.BeginTran//单库
 db.BeginTran //多库事务
 db.AsTenant().BeginTran()//多库事务 一般是接口ISqlSugarClient使用

SqlSugarClient事务

     因为继承 ITenant 了可以直接使用 (老版本var mysql=db.GetConnection要写在事务外面)

db.Ado.BeginTran//单库
 db.BeginTran //多库事务
 db.AsTenant().BeginTran()//多库事务 一般是接口ISqlSugarClient使用

“笑对人生,智慧同行!博客新文出炉,微信订阅号更新更实时,等你笑纳~”
在这里插入图片描述

  • 26
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

拥有必珍惜

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值