C#-了解ORM框架SqlSugar并巧妙使用(附相关数据库工具)

目录

一、配置

二、操作步骤

1、根据配置映射数据库对象

2、实体配置

3、创建表

4、增删改查

增加数据

删除数据

更新数据

查询数据

5、导航增删改查

增加数据

删除数据

更新数据

查询数据

6、雪花ID

三、工具

SqlLite可视化工具

MySQL安装包

MySQL可视化工具

SqlServer安装


SqlSugar官方文档:ORM 查询体系 、最简单、最强大 - SqlSugar 5x - .NET果糖网

一、配置

1、Nuget包添加SqlSugar

2、App.config添加配置

XML 复制代码
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
    </startup>
	<connectionStrings>
		<!--sqlite数据库字符串,路径符号|DataDirectory|代表当前运行目录-->
		<add name="sqlite" providerName="System.Data.SQLite" connectionString="Data Source=|DataDirectory|\TestData.db;Version=3;" />
		<!--Sqlserver数据库的连接字符串-->
		<add name="sqlserver" providerName="System.Data.SqlClient" connectionString="Persist Security Info=False;Data Source=(local);Initial Catalog=TestData;Integrated Security=SSPI" />
		<!--MySQL数据库的连接字符串-->
		<add name="mysql" providerName="MySql.Data.MySqlClient" connectionString="Server=localhost;Database=TestData;Uid=root;Pwd=123456;SslMode=none" />
		<!--PostgreSQL数据库的连接字符串-->
		<add name="npgsql" providerName="Npgsql" connectionString="Server=localhost;Port=5432;Database=TestData;User Id=root;Password=123456" />
		<!--不受驱动影响,32位64位均可使用-->
		<add name="oracle" providerName="OracleManaged" connectionString="Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=orcl)));User ID=auston;Password=123456" />
		<!--达梦数据库的连接字符串-->
		<add name="Dm" providerName="Dm" connectionString="Server=localhost;User ID=auston;PWD=123456;Database=CSPData;" />
	</connectionStrings>
	<appSettings>
		<!--指定默认的数据库类型,如果不指定则使用第一个连接字符串-->
		<add key="DbType" value="sqlite" />
		<add key="ClientSettingsProvider.ServiceUri" value="" />
	</appSettings>
</configuration>

二、操作步骤

1、根据配置映射数据库对象

cs 复制代码
        private void Connect()
        {
            try
            {
                var db = ConfigurationManager.AppSettings.Get("DbType");
                var connectStr = ConfigurationManager.ConnectionStrings[db].ConnectionString;
                DbType dbType = DbType.Sqlite;
                switch (db)
                {
                    case "sqlite":
                        dbType = DbType.Sqlite;
                        break;
                    case "mysql":
                        dbType = DbType.MySql;
                        break;
                    case "sqlserver":
                        dbType = DbType.SqlServer;
                        break;
                }
                sqlSugarScope = new SqlSugarScope(new ConnectionConfig()
                {
                    ConnectionString = connectStr,
                    DbType = dbType,
                    IsAutoCloseConnection = true,//自动释放数据务,如果存在事务,在事务结束后释放
                    InitKeyType = InitKeyType.Attribute,//从实体特性中读取主键自增列信息
                });
            }
            catch (Exception)
            {

            }
        }

2、实体配置

**TableName:**指定表名(不指定默认类名)

ColumnName:指定列名(不指定默认属性名)

IsPrimaryKey:是否设为主键

cs 复制代码
        [SugarTable(TableName = "Student")]
        public class Student
        {
            [SugarColumn(ColumnName = "ID",IsPrimaryKey =true)]
            public string Id { get; set; }

            [SugarColumn(ColumnName = "Name")]
            public string Name { get; set; }
        }

3、创建表

cs 复制代码
        private void CreateTable(int len, params Type[] types)
        {
            //设置varchar的默认长度
            sqlSugarScope.CodeFirst.SetStringDefaultLength(len);
            //sqlSugarScope.CodeFirst.BackupTable().InitTables(types);//备份表
            sqlSugarScope.CodeFirst.InitTables(types);
        }

4、增删改查

增加数据
cs 复制代码
        private void AddOne(Student stu)
        {
            sqlSugarScope.Insertable<Student>(stu).ExecuteCommand();
        }
删除数据
cs 复制代码
private void Delete(int id)
{
    sqlSugarScope.Deleteable<Student>().Where(s=>s.Id.Equals(id)).ExecuteCommand();
}
更新数据
cs 复制代码
        private void Update(Student stu)
        {
            //根据主键更新
            sqlSugarScope.Updateable<Student>(stu).ExecuteCommand();
            //据主键更新指定列
            //sqlSugarScope.Updateable<Student>(stu).UpdateColumns(i => new { i.Id,i.Name}).ExecuteCommand();
            //根据指定列更新
            //sqlSugarScope.Updateable<Student>(stu).WhereColumns(i=>new { i.Name}).ExecuteCommand();
            //根据指定条件更新
            //sqlSugarScope.Updateable<Student>(stu).Where(i => i.Age.Equals(18)).ExecuteCommand();
            //据主键更新忽略指定列
            //sqlSugarScope.Updateable<Student>(stu).IgnoreColumns(i=>new { i.Age}).ExecuteCommand();
        }
查询数据
cs 复制代码
var stus= sqlSugarScope.Queryable<Student>().Where(i => i.Age.Equals(22)).ToList();

5、导航增删改查

增加数据

NavigateType:指定导航类型

nameof():绑定Id用于导航

IsIdentity:是否自增

cs 复制代码
        private void AddNav()
        {
            var books1 = new List<Book>()
            {
                new Book(){ Name="BookA"},
                new Book(){ Name="BookB"},
                new Book(){ Name="BookC"},
            };
            var books2 = new List<Book>()
            {
                new Book(){ Name="BookK"},
                new Book(){ Name="BookP"},
                new Book(){ Name="BookZ"},
            };
            sqlSugarScope.InsertNav<Student>(new Student() { Name = "GGBom", Books = books1 }).Include(i => i.Books).ExecuteCommand();
            sqlSugarScope.InsertNav<Student>(new Student() { Name = "LuBi", Books = books2 }).Include(i => i.Books).ExecuteCommand();
        }

        [SugarTable(TableName = "Student")]
        public class Student
        {
            [SugarColumn(ColumnName = "ID", IsPrimaryKey = true, IsIdentity = true)]
            public int Id { get; set; }

            public string Name { get; set; }

            public int Age { get; set; }

            [Navigate(NavigateType.OneToMany, nameof(Book.StudentId))]
            public List<Book> Books { get; set; }
        }

        public class Book
        {
            [SugarColumn( IsPrimaryKey = true, IsIdentity = true)]
            public int BookId { get; set; }
            public string Name { get; set; }
            public int StudentId { get; set; }
        }
删除数据
cs 复制代码
private void DeleteNav(int age)
{
    sqlSugarScope.DeleteNav<Student>(i => i.Age.Equals(age)).Include(m => m.Books).ExecuteCommand();
}
更新数据
cs 复制代码
        private void UpdateNav()
        {
            var books = new List<Book>()
            {
                new Book(){ Name="BookNew1"},
                new Book(){ Name="BookNew2"},
                new Book(){ Name="BookNew3"},
            };
            sqlSugarScope.UpdateNav<Student>(new Student() {Id=1, Name="Lucy",Books=books}).Include(i => i.Books).ExecuteCommand();
        }
查询数据
cs 复制代码
var stus= sqlSugarScope.Queryable<Student>().Where(i => i.Age.Equals(22))
     .Includes(i => i.Books)
     .ToList();

6、雪花ID

设置WorkId

cs 复制代码
            //程序启时动执行一次就行
            //从配置文件读取一定要不一样
            //服务器时间修改一定也要修改WorkId
            SnowFlakeSingle.WorkId = 1;

long类型主键自动赋值

cs 复制代码
[SugarColumn(ColumnName = "ID", IsPrimaryKey = true)]
public long Id { get; set; }//long类型的主键会自动赋值

long没有19位长度,序列化雪花ID时要序列化成string

cs 复制代码
[Newtonsoft.Json.JsonConverter(typeof(ValueToStringConverter))] 
[SugarColumn(ColumnName = "ID", IsPrimaryKey = true)]
public long Id { get; set; }//long类型的主键会自动赋值

插入返回雪花ID

cs 复制代码
long id= db.Insertable(实体).ExecuteReturnSnowflakeId();//单条插入返回雪花ID
List<Long> ids=db.Insertable(List<实体>).ExecuteReturnSnowflakeIdList();//多条插入批量返回,比自增好用

手动调雪花ID

cs 复制代码
var id=SnowFlakeSingle.Instance.NextId();//也可以在程序中直接获取ID

自定义雪花算法:

cs 复制代码
  //程序启动时执行一次就行
  StaticConfig.CustomSnowFlakeFunc = () =>
  {
      return 你的雪花ID方法();
  };

三、工具

SqlLite可视化工具

链接: 百度网盘 请输入提取码

提取码: xvsc

MySQL安装包

链接: 百度网盘 请输入提取码

提取码: 97uh

MySQL可视化工具

链接: 百度网盘 请输入提取码

提取码: 1afx

SqlServer安装

链接: 百度网盘 请输入提取码

提取码: i5sj

相关推荐
楠神说软件测试27 分钟前
MySQL调优
数据库·mysql
Cedric_Anik1 小时前
MYSQL数据库基础篇——DDL
数据库·mysql
文牧之1 小时前
PostgreSQL的walsender和walreceiver进程介绍
运维·数据库·postgresql
爬山算法1 小时前
Oracle(121)如何进行数据文件的恢复?
数据库·oracle
咔咔学姐kk1 小时前
2024最新版,人大赵鑫老师《大语言模型》新书pdf分享
数据库·人工智能·语言模型·自然语言处理·pdf·知识图谱·产品经理
青云交1 小时前
大数据新视界 --大数据大厂之MongoDB与大数据:灵活文档数据库的应用场景
大数据·数据库·mongodb·非关系型数据库·文档存储·查询功能、数据处理·开发效率、应用场景、高可扩展性
青云交2 小时前
大数据新视界 --大数据大厂之HBase深度探寻:大规模数据存储与查询的卓越方案
大数据·数据库·hbase·数据存储·性能优势、问题解决、应用领域·可扩展性、高可靠性·读写性能、集群管理
茜茜西西CeCe2 小时前
大数据处理技术:HBase的安装与基本操作
java·大数据·数据库·hbase·头歌·大数据处理技术
shangan_32 小时前
黑马十天精通MySQL知识点
数据库·mysql
Jasonakeke2 小时前
【重学 MySQL】三十一、字符串函数
数据库·mysql