赞
踩
目录
SqlSugar 是一款 老牌 .NET 开源ORM框架,由果糖大数据科技团队维护和更新 ,开箱即用
最易上手的ORM框架
支持的数据库:MySql、SqlServer、Sqlite、Oracle 、 postgresql等
nuget安装SqlSugarCore
控制台应用程序
.NET6.0
Mysql:8.0.25
- public class SqlSugarHelper
- {
- //相比SqlSugarClient, SqlSugarScope是线程安全的
- //用单例模式 SqlSugarScope一直new会内存泄露 一定要用单例
- public static SqlSugarScope Db = new SqlSugarScope(new ConnectionConfig()
- {
- //连接符字串
- ConnectionString = "server=localhost;Database=SqlSugarDemo;Uid=root;Pwd=hirosedb;AllowLoadLocalInfile=true;",
- //数据库类型
- DbType = DbType.MySql,
- //不设成true要手动close
- IsAutoCloseConnection = true,
- },
- db =>
- {
- //(A)全局生效配置点,一般AOP和程序启动的配置扔这里面 ,所有上下文生效
- //调试SQL事件,可以删掉
- //sql执行前
- db.Aop.OnLogExecuting = (sql, pars) =>
- {
- Console.WriteLine(sql);//输出sql,查看执行sql 性能无影响
- };
- //sql执行完
- db.Aop.OnLogExecuted = (sql, pars) =>
- {
- Console.WriteLine($"执行时间:{db.Ado.SqlExecutionTime.TotalMilliseconds}");
- };
- //sql报错
- db.Aop.OnError = (exp) =>
- {
- Console.WriteLine(exp.Sql);
- };
- });
- }
- [SugarTable("student")] //当实体和数据库表名称不一样时可以设置表别名 指定表名
- public class Student
- {
- [SugarColumn(IsPrimaryKey =true,IsIdentity =true)] //主键、自增
- public int Id { get; set; }
- [SugarColumn(ColumnName ="StuName")] //数据库与实体不一样设置列名
- public string Name { get; set; }
- [SugarColumn(IsIgnore =true)] //表示 ORM 所有操作不处理这列 一般用于数据库没有这一列
- public int StudentId { get; set; }
-
- }
- var db = SqlSugarHelper.Db;
-
- //创建数据库,不存在:创建, 存在:不会重复创建
- //会根据连接字符串中的数据库进行创建
- db.DbMaintenance.CreateDatabase();
- //根据实体类创建表
- db.CodeFirst.InitTables(typeof(Student));
- //返回插入行数
- var stu2 = new Student() { Name = "eeee" };
- db.Insertable(stu2).ExecuteCommand();
- //用AS来强制设置表名(默认表名来自实体)
- db.Insertable(stu2).AS("student").ExecuteCommand();
-
- //批量插入 List
- var stu3 = new List<Student>() { new Student() { Name = "批量1" }, new Student() { Name = "批量2" } };
- db.Insertable(stu3).ExecuteCommand();
-
- //异步
- await db.Insertable(stu2).ExecuteCommandAsync();
- //条件删除
- db.Deleteable<Student>().Where(it => it.Id == 1).ExecuteCommand();
-
- //根据主键删除
- db.Deleteable<Student>().In(2).ExecuteCommand();
-
- //异步 根据主键数组删除
- await db.Deleteable<Student>().In(new int[] { 3, 4 }).ExecuteCommandAsync();
- var stu4 = new Student() { Id=3, Name = "aaaa" };
- //根据主键更新单条
- db.Updateable(stu4).ExecuteCommand();
- var stu5 = new List<Student>() { new Student() { Id = 3, Name = "BBB" }, new Student() { Id = 4, Name = "CCC" } };
- //批量更新 List
- db.Updateable(stu5).ExecuteCommand();
-
- //异步
- await db.Updateable(stu5).ExecuteCommandAsync();
-
- //按条件更新
- db.Updateable(stu2).Where(it => it.Id > 5 && it.Id < 10).ExecuteCommand();
-
- //指定某列更新 只更新name条件id=10
- db.Updateable<Student>().SetColumns(it => it.Name == "指定列更新").Where(it => it.Id == 10).ExecuteCommand();
- //查所有
- db.Queryable<Student>().ToList();
- //按条件
- db.Queryable<Student>().Where(it => it.Id > 20).ToList();
- //多条件
- db.Queryable<Student>().Where(it => it.Id > 10 && it.Name == "eee").ToList();
- //查前5条
- db.Queryable<Student>().Take(5).ToList();
- //动态表达式
- Expression<Func<Student,bool>> exp=Expressionable.Create<Student>() //创建表达式
- .And(it=>it.Id>10) //逻辑 与
- .Or(it=>it.Id==6) //或
- .AndIF(true,it=>it.Name.Contains("ee")) //第一个参数是bool类型,即条件为ture 才会执行后面的表达式(第二个参数)
- .ToExpression();
- var stu7 = db.Queryable<Student>().Where(exp).ToList();
- Console.WriteLine(JsonConvert.SerializeObject(stu7));
-
- //异步 在原有方法后面加Async, 加await等待
- await db.Queryable<Student>().FirstAsync();
-
- //查询函数 使用SqlFunc这个类调用Sql函数.
- //.ToString .Contains .Length.ToLower .ToUpper .ToSubstring .Equals.HasValue.Replace.EndsWith.StartsWith.Trim等
- var stu8= db.Queryable<Student>().Where(it => SqlFunc.Contains(it.Name, "ee")).ToList();
- Console.WriteLine(JsonConvert.SerializeObject(stu8));
- //使用db.Ado
- //查询
- var sql = "select * from student where id>10";
- var stu6= db.Ado.SqlQuery<Student>(sql);
- Console.WriteLine(JsonConvert.SerializeObject(stu6));
- //插入 更新 删除
- sql = "DELETE FROM student WHERE id>30";
- db.Ado.ExecuteCommand(sql);
- try
- {
- db.BeginTran();
-
- db.Updateable(new Student() { Id = 2, Name = "update" }).ExecuteCommand();
-
- db.CommitTran();
-
- }
- catch (Exception ex)
- {
- Console.WriteLine($"ex:{ex.Message} st:{ex.StackTrace}" );
- db.RollbackTran(); //数据回滚
- }
nuget安装SqlSugar.IOC
- SugarIocServices.AddSqlSugar(new IocConfig()
- {
- //ConfigId = "db01", 多租户用到
- ConnectionString = "server=localhost;Database=SqlSugarDemo;Uid=root;Pwd=hirosedb;",
- DbType = IocDbType.MySql,
- IsAutoCloseConnection = true,
- }); //多个库传入List<IocConfig>
-
-
- //配置参数
- SugarIocServices.ConfigurationSugar(db =>
- {
- db.Aop.OnLogExecuting = (sql, p) =>
- {
- Console.WriteLine(sql);
- };
- });
-
-
- //注入后使用 DbScoped.SugarScope相当于SqlSugarScope
- DbScoped.SugarScope.Insertable(new Student() { Name = "wwww" }).ExecuteCommand();
- var stu1 = DbScoped.SugarScope.Queryable<Student>().Where(it => it.Id > 1).ToList();
- Console.WriteLine(JsonConvert.SerializeObject(stu1));
参考:SqlSugar ORM 5.X 官网 、文档、教程 - SqlSugar 5x - .NET果糖网 (donet5.com)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。