.net6 SqlSugar配置及增删改查(webapi项目)

文章介绍了如何在.NET中使用SqlSugarCore库进行数据库操作,包括配置连接、生成实体类、CRUD操作以及关联和模糊查询。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

NuGet包:

1.SqlSugarCore

2.System.Data.SqlClient

Program配置:

builder.Services.AddScoped<ISqlSugarClient>(x =>
{
    SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
    {
        ConnectionString = "Data Source=.;Initial Catalog=hx;Integrated Security=True;TrustServerCertificate=True", // 替换为实际的数据库连接字符串
        DbType = DbType.SqlServer, // 数据库类型,这里以 SQL Server 为例
        IsAutoCloseConnection = true, // 自动关闭连接
        MoreSettings = new ConnMoreSettings()
        {
            IsWithNoLockQuery = true, // 默认查询时加上 WITH (NOLOCK)
            IsAutoRemoveDataCache = true// 自动清除缓存
        }
    });
    // 配置输出 SQL 语句到控制台
    db.Aop.OnLogExecuting = (sql, pars) =>
    {
        Console.WriteLine($"Executing SQL: {sql}\nParameters: {JsonSerializer.Serialize(pars)}\n");
    };

    return db;
});

生成实体类:

可以放在一个控制台程序中,需要的时候在运行就好

using SqlSugar;
using DbType = SqlSugar.DbType;

// 配置连接字符串
var db = new SqlSugarClient(new ConnectionConfig()
{
    ConnectionString = "Data Source=.;Initial Catalog=hx;Integrated Security=True;TrustServerCertificate=True",//数据库连接字符串
    DbType = DbType.SqlServer, // 数据库类型,这里以 SQL Server 为例
    IsAutoCloseConnection = true, // 自动关闭连接
    InitKeyType = InitKeyType.Attribute // 通过特性标识主键
});
// DbFirst是SQLSugar中的一个功能,可以让我们通过数据库表自动生成实体类(生成全部表)
db.DbFirst.CreateClassFile("生成文件路径", "命名空间");

//只生成YourTable表(要生成某个表直接改YourTable替换成要生成的表名)
db.DbFirst.Where("TableName='YourTable'").CreateClassFile("生成文件路径", "命名空间");

//不生成YourTable表
db.DbFirst.Where("YourTable").CreateClassFile("生成文件路径", "命名空间");

增:

 [HttpPost]
 public IActionResult Insert(Student add)//添加使用的是实体类
 {
     var result = _sqlSugarClient.Insertable(add)
                 .IgnoreColumns(it => it.ID)//不添加此字段
                 .ExecuteCommand() > 0;
     JsonResult json = new JsonResult(new
     {
         msg = result ? "ok" : "no"
     });
     return json;
 }

删:

  [HttpPost]
  public IActionResult Delete(int id)
  {
      bool result = _sqlSugarClient
          .Deleteable<Student>(x => x.ID == id)//删除行的id
          .ExecuteCommandHasChange();
      JsonResult json = new JsonResult(new
      {
          msg = result ? "ok" : "no"
      });
      return json;
  }

改:

 [HttpPost]
 public IActionResult UpdateStudent(Stu_Update update)//修改使用DTO
 {
     var result = _sqlSugarClient.Updateable<Student>()
                  .SetColumns(it => new Student { Name = update.Name }) // 设置要更新的字段及其值
                  .Where(it => it.ID == update.ID) // 提供更新条件
                  .ExecuteCommandHasChange();
     JsonResult json = new JsonResult(new
     {
         msg = result ? "ok" : "no"
     });
     return json;
 }

查(内连):

 [HttpGet]
 public IActionResult Select()
 {
     var result = _sqlSugarClient.Queryable<Student, Classes, Teacher>((t1, t2, t3) => t1.ClassId == t2.ID && t2.ID == t3.ClassId)//关联条件
                                 .Select((t1, t2, t3) => new Stu
                                 {
                                     ID = t1.ID,
                                     Name = t1.Name,
                                     ClassName = t2.Name,
                                     TeacherName = t3.Name
                                 })
                                 .ToList();
     JsonResult json = new JsonResult(new
     {
         msg = result
     });
     return json;
 }

查(左联):

  [HttpGet]
  public IActionResult Select()
  {
      var result = _sqlSugarClient.Queryable<Student, Classes, Teacher>((t1, t2, t3) => new JoinQueryInfos(
                                      JoinType.Left, t1.ClassId == t2.ID, //左连接 左链接 左联
                                      JoinType.Left, t2.ID == t3.ID
                                  ))//关联条件
                                 .Select((t1, t2, t3) => new Stu
                                 {
                                     ID = t1.ID,
                                     Name = t1.Name,
                                     ClassName = t2.Name,
                                     TeacherName = t3.Name
                                 })
                                 .ToList();
      JsonResult json = new JsonResult(new
      {
          msg = result
      });
      return json;
  }

查(模糊查询):

[HttpGet]
public IActionResult Select_S(string Name)
{
    var result = _sqlSugarClient.Queryable<Student, Classes, Teacher>((t1, t2, t3) => new JoinQueryInfos(
                                    JoinType.Left, t1.ClassId == t2.ID, //左连接 左链接 左联
                                    JoinType.Left, t2.ID == t3.ID
                                ))//关联条件
                               .Select((t1, t2, t3) => new Stu
                               {
                                   ID = t1.ID,
                                   Name = t1.Name,
                                   ClassName = t2.Name,
                                   TeacherName = t3.Name
                               }).ToList();
    if (Name != null)
    {
        result = result.Where(x => x.Name.Contains(Name)).ToList();//模糊查询
    }
    JsonResult json = new JsonResult(new
    {
        msg = result
    });
    return json;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值