.Net8框架使用Web Core API项目引用SqlSugar教程

作者 : admin 本文共8361个字,预计阅读时间需要21分钟 发布时间: 2024-06-17 共1人阅读

.Net8 Web Core API项目使用SqlSugar教程

  • 说明
    • 创建项目
    • 配置依赖包
    • 编写代码
    • 页面调用
    • 实体建表

说明

本文档做入门教程,实现了如何在web环境中搭建,引用SqlSugar并进行增删改查、实体建表、主从哭查询等基础操作,对于丰富的SqlSugar API来说是冰山一角。

如想吃透这框架还请去SqlSugar官网中学习,地址:https://www.donet5.com/Home/Doc。

在研究的时候,在代码中写了详细的注释,注释内容文档中就不再说明了,自行阅读代码理解。

创建项目

创建一个web项目.Net8框架使用Web Core API项目引用SqlSugar教程插图

配置依赖包

1、右击刚才创建的项目,选择【管理NuGet程序包】
.Net8框架使用Web Core API项目引用SqlSugar教程插图(1)
2、在搜索框中输入:SqlSugar,安装SqlSugarCore.Net8框架使用Web Core API项目引用SqlSugar教程插图(2)

编写代码

1、在appsettings.json配置数据库的信息.Net8框架使用Web Core API项目引用SqlSugar教程插图(3)

2、创建数据库上下文,新建一个Context包,然后在其下创建DbContext类,此类负责数据库的连接和注册配置.Net8框架使用Web Core API项目引用SqlSugar教程插图(4)

using SqlSugar;
using System.Reflection;
namespace TestSugar.Context
{
public class DbContext
{
/*
1、SqlSugarClient 原生模式访问数据库(性能强)
2、SqlSugarScope 单例模式访问数据库(使用更简单,性能也不错)
决定用性能更强的SqlSugarClient
*/
public SqlSugarClient initDbContext(ConfigurationManager config,string? masterConnStr,string? slaveConnStr)
{
SqlSugarClient dbClient = new SqlSugarClient(new ConnectionConfig()
{
//定义数据库类型
DbType = DbType.SqlServer,
ConnectionString = config.GetConnectionString(masterConnStr),
IsAutoCloseConnection = true,//自动关闭连接
// 用于支持实体类中的 [SugarColumn] 特性
InitKeyType = InitKeyType.Attribute,
//从库
SlaveConnectionConfigs = new List<SlaveConnectionConfig>() {
new SlaveConnectionConfig() {ConnectionString=config.GetConnectionString(slaveConnStr)}
},
ConfigureExternalServices = new ConfigureExternalServices
{
//注意:  这儿AOP设置不能少
EntityService = (c, p) =>
{
/***高版C#写法
* 支持string?和string,实体字段没有加?代表建表时该字段不能为null
* ***/
if (p.IsPrimarykey == false && new NullabilityInfoContext().Create(c).WriteState is NullabilityState.Nullable)
{
p.IsNullable = true;
}
}
}
}, dbClient =>
{
dbClient.Aop.OnLogExecuted = (sql, pars) =>
{
//获取原生SQL推荐  性能OK
Console.WriteLine(UtilMethods.GetNativeSql(sql, pars));
//获取无参数化SQL 对性能有影响,特别大的SQL参数多的,调试使用
//Console.WriteLine(UtilMethods.GetSqlString(DbType.SqlServer,sql,pars))
};
});
return dbClient;
}
}
}

2、在Program.cs中依赖注入DbContext类.Net8框架使用Web Core API项目引用SqlSugar教程插图(5)

//IOC注入
/*  1 Transient - 每次请求都会被创建
2 Scoped - 每次每个客户端请求被创建
3 Singleton - 只创建一次*/
builder.Services.AddScoped<SqlSugarClient>(s =>
{
SqlSugarClient sqlSugar = new DbContext().initDbContext(builder.Configuration,"masterConnection","slaveConnection");
return sqlSugar;
});

4、新建Enitiy包,新建实体类User、Student
.Net8框架使用Web Core API项目引用SqlSugar教程插图(6)

using SqlSugar;
using System.ComponentModel.DataAnnotations.Schema;
using static System.Runtime.InteropServices.JavaScript.JSType;
namespace TestSugar.Entity
{
[SugarTable("Users")]
public class User
{
[SugarColumn(ColumnName ="Id",IsPrimaryKey = true)]
public string? Id { get; set; }
public string? No { get; set; }
public string? Name { get; set; }
public int Age { get; set; }
public string? Sex { get; set; }
}
}
using SqlSugar;
using System.ComponentModel.DataAnnotations.Schema;
using static System.Runtime.InteropServices.JavaScript.JSType;
namespace TestSugar.Entity
{
//Data Annotation方式
[Table("Student", Schema = "dbo")]//指定表
public class Student
{
[SugarColumn(ColumnName = "Id", IsPrimaryKey = true)]
public string? Id { get; set; }
//[SugarColumn(IsNullable = true)]
public string? No { get; set; }
//[SugarColumn(IsNullable = true)]
public string? Name { get; set; }
[SugarColumn(IsIdentity = true)]
public int Age { get; set; }
//[SugarColumn(IsNullable = true)]
[SugarColumn(ColumnName = "Sex")]
public string? Sex { get; set; }
}
}

5、我们在User中实现增删改查,在Student中实现自动建表。所以先看User部分。我们可以像以往一样手动的在数据库工具中建立一张Users表,字段和实体对应。
.Net8框架使用Web Core API项目引用SqlSugar教程插图(7)
6、表建好之后,我们开始用代码来操作增删改查,我们需要在项目的Controllers包中增加UserController类.Net8框架使用Web Core API项目引用SqlSugar教程插图(8)

using Microsoft.AspNetCore.Mvc;
using System.Linq.Expressions;
using System.Net;
using System.Reflection.Metadata;
using TestSugar.Context;
using TestSugar.Entity;
using SqlSugar;
namespace TestEFCore.Controllers
{
[ApiController]
[Route("api/[controller]/[Action]")]
public class UserController : ControllerBase
{
/* 注入SqlSugarClient
用法和Dapper、Ado、EF一样 ,不能单例,每个上下文都要是新的对象拥有超高性能,
使用不当出现偶发错误通过IOC或者db.CopyNew()创建新的对象避免同一个对象在多个上下文使用 ,禁止单例*/
private readonly SqlSugarClient isc;
public UserController(SqlSugarClient context)
{
isc = context;
}
//查询
[HttpGet]
public IEnumerable<User> getAllUser_01()
{
return isc.Queryable<User>().ToList();
}
//异步查询
[HttpGet]
public async Task<IEnumerable<User>> getAllUser_02()
{
return await isc.Queryable<User>().ToListAsync();
}
//查询,用于解决线程问题
[HttpGet]
public IEnumerable<User> getAllUser_03()
{
var newdb = isc.CopyNew();
return newdb.Queryable<User>().ToList();
}
[HttpGet]
public IEnumerable<User> getAllUser_04()
{
using (var db = isc.CopyNew())
{
return isc.Queryable<User>().ToList();
}
}
//查询条件
[HttpGet]
public IEnumerable<User> getUserByName(String name)
{
//LINQ
return isc.Queryable<User>().Where(s => s.Name == name).ToList();
}
//增加
[HttpPost]
public String addUser(String no, String name, int age, String sex)
{
Guid guid = Guid.NewGuid();
try
{
isc.BeginTran();//开启事务
var user = new User { Id = guid.ToString("N"), No = no, Name = name, Age = age, Sex = sex };
int i = isc.Insertable<User>(user).ExecuteCommand();
if (i > 0)
{
isc.CommitTran();//提交事务
return "ok";
}
else
{
return "新增失败";
}
}
catch (Exception ex)
{
isc.RollbackTran();//回滚
return "添加数据发生了错误:" + ex.Message.ToString();
}
}
//修改 异步
[HttpPost]
public async Task<String> updateUserById(String id, String? no, String? name, String? age, String? sex)
{
try
{
await isc.BeginTranAsync();//异步事务
var user = await isc.Queryable<User>().Where(s => s.Id == id).FirstAsync();
if (user == null)
{
return "未找到指定数据";
}
if (no != null && no != "")
{
user.No = no;
}
if (name != null && name != "")
{
user.Name = name;
}
if (age != null && age != "")
{
user.Age = int.Parse(age);
}
if (sex != null && sex != "")
{
user.Sex = sex;
}
int i = await isc.Updateable<User>(user).WhereColumns(u => u.Id).ExecuteCommandAsync();//异步修改,必须给个WhereColumns(u => [字段]),字段最好给不会去修改的,如果给的字段正好参与修改,则修改会失效。
if (i > 0)
{
await isc.CommitTranAsync();//异步提交
return "ok";
}
else
{
return "未找到指定数据";
}
}
catch (Exception ex)
{
await isc.RollbackTranAsync();//回滚
return "修改数据发生了错误:" + ex.Message.ToString();
}
}
//删除 UseTran 自动回滚
[HttpPost]
public String delUserById_01(String id)
{
try
{
using (var tran = isc.UseTran())
{
int i = isc.Deleteable<User>().Where(s => s.Id == id).ExecuteCommand();
if (i > 0)
{
tran.CommitTran();//需要手动提交
return "ok";
}
else
{
return "未找到指定数据";
}
}
}
catch (Exception ex)
{
return "删除数据发生了错误:" + ex.Message.ToString();
}
}
//删除  自动提交、回滚
[HttpPost]
public String delUserById_02(String id)
{
int i = 0;
var result = isc.UseTran(() =>//自动提交
{
i = isc.Deleteable<User>().Where(s => s.Id == id).ExecuteCommand();
});
if (result.IsSuccess)
{
if (i > 0)
{
return "ok";
}
else
{
return "未找到指定数据";
}
}
else
{
return "fail";
}
}
//删除 UseTranAsync异步 自动提交、回滚
[HttpPost]
public async Task<String> delUserById_03(String id)
{
int i = 0;
var result = await isc.UseTranAsync(async () =>//自动提交
{
i = await isc.Deleteable<User>().Where(s => s.Id == id).ExecuteCommandAsync();
//throw new Exception("");//走失败
});
if (result.IsSuccess)
{
if (i > 0)
{
return "ok";
}
else
{
return "未找到指定数据";
}
}
else
{
return "fail";
}
}
}
}

7、接下来将项目设为启动项,然后启动项目.Net8框架使用Web Core API项目引用SqlSugar教程插图(9)
8、浏览器就会跳转打开这个界面了,在里面我们可以看到写的接口函数
.Net8框架使用Web Core API项目引用SqlSugar教程插图(10)

页面调用

1、新增user
.Net8框架使用Web Core API项目引用SqlSugar教程插图(11)
2、选择尝试按钮.Net8框架使用Web Core API项目引用SqlSugar教程插图(12)3、填入参数,选择提交.Net8框架使用Web Core API项目引用SqlSugar教程插图(13)
4、结果中出现ok,表示成功.Net8框架使用Web Core API项目引用SqlSugar教程插图(14)5、去数据库看看,可以看到真的添加了一笔,新增完成!.Net8框架使用Web Core API项目引用SqlSugar教程插图(15)
6、删除、查询、修改,都是一样的页面操作,就不介绍了。

实体建表

1、添加StudentController类.Net8框架使用Web Core API项目引用SqlSugar教程插图(16)

using Microsoft.AspNetCore.Mvc;
using System.Linq.Expressions;
using System.Net;
using System.Reflection.Metadata;
using TestSugar.Context;
using TestSugar.Entity;
using SqlSugar;
namespace TestEFCore.Controllers
{
[ApiController]
[Route("api/[controller]/[Action]")]
public class StudentController : ControllerBase
{
/* 注入SqlSugarClient
用法和Dapper、Ado、EF一样 ,不能单例,每个上下文都要是新的对象拥有超高性能,
使用不当出现偶发错误通过IOC或者db.CopyNew()创建新的对象避免同一个对象在多个上下文使用 ,禁止单例*/
private readonly SqlSugarClient isc;
public StudentController(SqlSugarClient context)
{
isc = context;
}
//建表
[HttpPost]
public String createTable()
{
try
{
isc.CodeFirst.As<Student>("Student2").InitTables<Student>();
}
catch (Exception ex)
{
return "添加数据发生了错误:" + ex.Message.ToString();
}
return "ok";
}
//增加
[HttpPost]
public String addStu(String no, String name, String sex)
{
Guid guid = Guid.NewGuid();
try
{
isc.BeginTran();//开启事务
var stu = new Student { Id = guid.ToString("N"), No = no, Name = name, Sex = sex };
isc.Insertable<Student>(stu).ExecuteCommand();
isc.CommitTran();//提交事务
}
catch (Exception ex)
{
isc.RollbackTran();//回滚
return "添加数据发生了错误:" + ex.Message.ToString();
}
return "ok";
}
//增加
[HttpPost]
public String addStu_02(String no, String name, String sex)
{
Guid guid = Guid.NewGuid();
try
{
isc.BeginTran();//开启事务
var stu = new Student { Id = guid.ToString("N"), No = no, Name = name, Sex = sex };
isc.Insertable<Student>(stu).AS("Student2").ExecuteCommand();
isc.CommitTran();//提交事务
}
catch (Exception ex)
{
isc.RollbackTran();//回滚
return "添加数据发生了错误:" + ex.Message.ToString();
}
return "ok";
}
//查询
[HttpGet]
public IEnumerable<Student> getAllStu_01()
{   //默认查主库
return isc.Queryable<Student>().ToList();
}
[HttpGet]
public IEnumerable<Student> getAllStu_02()
{   //查从库
return isc.SlaveQueryable<Student>().ToList();
}
}
}

2、运行项目,选择创建学生表.Net8框架使用Web Core API项目引用SqlSugar教程插图(17)
3、选择尝试按钮.Net8框架使用Web Core API项目引用SqlSugar教程插图(18)4、在提交之前我删除了之前创建的学生表,现在刷新看下数据库是没有student这张表的.Net8框架使用Web Core API项目引用SqlSugar教程插图(19)
5、点击提交.Net8框架使用Web Core API项目引用SqlSugar教程插图(20)
6、刷新数据库看到,多了一张Student2表,createTable函数中也是这个名字所以没问题,建表成功!学生这里还实现了主从库的查询,代码都写好了直接运行即可,我这里就不一一演示了。.Net8框架使用Web Core API项目引用SqlSugar教程插图(21).Net8框架使用Web Core API项目引用SqlSugar教程插图(22).Net8框架使用Web Core API项目引用SqlSugar教程插图(23)## 总结
以上代码都可以粘贴复制到环境中使用,我用的是sql server2019数据库切换也很方面,如果换成其它种类数据库,只需要把 DbContext中的DbType = DbType.SqlServer,这一行的SqlServer替换成你的数据库就行,共有这么多选择。

public enum DbType
{
MySql = 0,
SqlServer = 1,
Sqlite = 2,
Oracle = 3,
PostgreSQL = 4,
Dm = 5,
Kdbndp = 6,
Oscar = 7,
MySqlConnector = 8,
Access = 9,
OpenGauss = 10,
QuestDB = 11,
HG = 12,
ClickHouse = 13,
GBase = 14,
Odbc = 15,
OceanBaseForOracle = 16,
TDengine = 17,
GaussDB = 18,
OceanBase = 19,
Tidb = 20,
Vastbase = 21,
PolarDB = 22,
Doris = 23,
Custom = 900
}
本站无任何商业行为
个人在线分享-虚灵IT资料分享 » .Net8框架使用Web Core API项目引用SqlSugar教程
E-->