SqlSugar基础用法

SQLSugar是什么

**1. 轻量级ORM框架,专为.NET CORE开发人员设计,它提供了简单、高效的方式来处理数据库操作,使开发人员能够更轻松地与数据库进行交互

2. 简化数据库操作和数据访问,允许开发人员在C#代码中直接操作数据库,而不需要编写复杂的SQL语句

3. 支持多种数据库,包括但不限于MYSQL、SQLSERVER、SQLITE、ORACLE等**

使用SQLSugar的优点与缺点

优点:

1. 高性能:相比EF等ORM框架,SQLSUGAR在性能上表现出色。在大数据的写入、更新和查询统计方面,SQLSUGAR的性能是EF的数倍。此外,它在批量操作和一对多查询上也进行了不错的SQL优化。

2. 高扩展性:SQLSUGAR支持自定义拉姆达函数解析、扩展数据类型、自定义实体特性,以及外部缓存等功能,这些都使得其具有较高的可扩展性。

3. 稳定性:虽然不是官方的ORM框架,但SQLSUGAR在稳定性上也有着数年用户积累。如果遇到问题,可以在GITHUB上提出,开发者会根据紧急度定期解决。

4. 功能全面:虽然SQLSUGAR体积小巧,但其功能并不逊色于其他大型ORM框架,如EF。

5. 生态丰富与多库兼容:SQLSUGAR支持多种数据库,为开发者提供了灵活的选择。同时,它还提供了详细的文档、教程以及专业技术支持,为开发者提供了全方位的服务。

6. 易用性:SQLSUGAR的使用非常简单,它提供了各种默认值作为最佳配置,开发者只需关注自己的业务逻辑即可。这种易用性大大降低了学习成本,提高了开发效率。

缺点

没啥大缺点

SQLSugar基础使用

安装SQLSugarCore包

image

创建上下文类

image

配置链接字符串--这块有点坑、以下这种格式可能会爆错、SLL证书错误

image

以下是我的链接字符串

Data Source=.;Initial Catalog=SQLSugarDemo;Integrated Security=True;Trust Server Certificate=True

image

注册SQLSugar--我封装了Ioc

image
image

在控制器定义方法进行迁移数据库

image
image
image

当然你也可以用命令进行迁移

Sugar迁移命令:
dotnet ef migrations add 生成文件夹名称 --project SqlSugarTests.WebAPI.csproj
dotnet ef database update
迁移命令有点麻烦还不一定能迁移成功,可以用ef或者方法进行迁移

以下是基础用法(增删改查)

我大概是给整复杂了,我封装了一下、我再研究研究给整简单点

定义泛型接口

image

接口与实现

image
``

点击查看代码
 public interface IRepository<T> where T : class,new()
 {
     // 插入(增)  
     Task<int> Insert(T entity);
     // 根据ID查询(查)  
     Task<T> GetById(int id);
     //删除
     Task<int> DeleteById(int id);

     // 更新(改)  
     Task<bool> Update(T entity, Expression<Func<T, bool>> whereCondition);

     // 删除(删)  
     Task<bool> Delete(Expression<Func<T, bool>> whereCondition);

     // 查询(查)  
     Task<T> Get(Expression<Func<T, bool>> whereCondition);

     // 查询列表  
     Task<List<T>> GetAll(Expression<Func<T, bool>> whereCondition = null);
     
 }

image
``

点击查看代码
public class Repository<T> : IRepository<T> where T : class, new()
{
    private readonly ISqlSugarClient _db;

    public Repository(ISqlSugarClient db)
    {
        _db = db;
    }
    // 插入(增)  
    public async Task<int> Insert(T entity)
    {
        try
        {
            return await _db.Insertable(entity).ExecuteCommandAsync();
        }
        catch (Exception ex)
        {
            // 处理异常或记录日志  
            throw;
        }
    }
    // 更新(改)  
    public async Task<bool> Update(T entity, Expression<Func<T, bool>> whereCondition)
    {
        try
        {
            var updateable = _db.Updateable(entity).Where(whereCondition);
            return await updateable.ExecuteCommandAsync() > 0;
        }
        catch (Exception ex)
        {
            // 处理异常或记录日志  
            throw;
        }
    }
    // 删除(删)  
    public async Task<bool> Delete(Expression<Func<T, bool>> whereCondition)
    {
        try
        {
            return await _db.Deleteable<T>().Where(whereCondition).ExecuteCommandAsync() > 0;
        }
        catch (Exception ex)
        {
            // 处理异常或记录日志  
            throw;
        }
    }
    // 查询(查)  
    public async Task<T> Get(Expression<Func<T, bool>> whereCondition)
    {
        try
        {
            return await _db.Queryable<T>().Where(whereCondition).SingleAsync();
        }
        catch (Exception ex)
        {
            // 处理异常或记录日志  
            return null;
        }
    }

    // 查询列表  
    public async Task<List<T>> GetAll(Expression<Func<T, bool>> whereCondition = null)
    {
        try
        {
            var query = _db.Queryable<T>();
            if (whereCondition != null)
            {
                query = query.Where(whereCondition);
            }
            return await query.ToListAsync();
        }
        catch (Exception ex)
        {
            // 处理异常或记录日志  
            return null;
        }
    }
    //查询单个
    public async Task<T> GetById(int id)
    {
        // 使用SQLSugar的Queryable API来获取单个实体  
        var result = _db.Queryable<T>().InSingle(id);
        // 注意:这里result已经是DepartmentModel的实例或null(如果没有找到)  
        // 因为InSingle是同步的,所以不需要await  
        return result;
    }
    /// <summary>
    /// 删除
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    public async Task<int> DeleteById(int id)
    {
        var result =_db.Deleteable<T>().In(id).ExecuteCommand();
        return result;
    }

    #region 其他扩展
    public async Task<bool> Delete<T1>(int id)
    {
        throw new NotImplementedException();
    }
    public async Task<List<T1>> GetAll<T1>()
    {
        throw new NotImplementedException();
    }
    public T1 GetById<T1>(int id)
    {
        throw new NotImplementedException();
    }
    public int Insert<T1>(T1 entity)
    {
        throw new NotImplementedException();
    }
    public bool Update<T1>(T1 entity, int? id = null)
    {
        throw new NotImplementedException();
    }
    #endregion

}

然后我封装了IocServer

这段代码主要做了两件事:

将ISqlSugarClient注册为Scoped服务到依赖注入容器中,并配置了数据库连接和AOP日志记录。

将SqlSugarContext(可能是一个封装了ISqlSugarClient的上下文类)也注册为Scoped服务,并确保它能够从DI容器中获取到ISqlSugarClient的实例。
image
``

点击查看代码
 public static void AddRepositoryServer(this WebApplicationBuilder builder)
 {
     // 直接注册 ISqlSugarClient 到 DI 容器  
     builder.Services.AddScoped<ISqlSugarClient>(sp => new SqlSugarClient(new ConnectionConfig()
     {
         ConnectionString = builder.Configuration.GetConnectionString("SQLSugar"), //数据库连接串
         DbType = DbType.SqlServer,      //数据库类型
         IsAutoCloseConnection = true, //自动释放
         MoreSettings = new ConnMoreSettings()
         {
             SqlServerCodeFirstNvarchar = true,//建表字符串默认Nvarchar
         }
     }, db =>
     {
         db.Aop.OnLogExecuting = (sql, pars) =>
         {
             Console.WriteLine(sql);//生成执行Sql语句
         };
     }
     ));
     builder.Services.AddScoped<SqlSugarContext>(sp => new SqlSugarContext(sp.GetRequiredService<ISqlSugarClient>()));
 }

在Program进行注册

image

控制器里使用

image
``

点击查看代码
public readonly SqlSugarContext db;
private readonly IRepository<DepartmentModel> _repository;
public SQLSugarController(SqlSugarContext context, IRepository<DepartmentModel> repository)
{

    this.db = context;
    this._repository = repository;
}
/// <summary>
/// 创建表
/// </summary>
/// <returns></returns>
[HttpGet("CreateTable")]
public IActionResult CreateTable()
{
    db.CreateTable();
    return Ok("执行成功!");
}
// 添加部门  
[HttpPost("AddDepartment")]
public async Task<IActionResult> AddDepartment([FromBody] DepartmentModel departmentModel)
{
    if (ModelState.IsValid)
    {
        int result = await _repository.Insert(departmentModel);
        if (result > 0)
        {
            return Ok(new { message = "部门添加成功", departmentId = departmentModel.DepartMentId });
        }
        else
        {
            return BadRequest(new { message = "部门添加失败" });
        }
    }
    else
    {
        return BadRequest(ModelState);
    }
}

// 更新部门  
[HttpPut("UpdateDepartment")]
public async Task<IActionResult> UpdateDepartment(int id, [FromBody] DepartmentModel departmentModel)
{
    if (ModelState.IsValid && departmentModel.DepartMentId == id)
    {
        bool result = await _repository.Update(departmentModel);
        if (result)
        {
            return Ok(new { message = "部门更新成功" });
        }
        else
        {
            return BadRequest(new { message = "部门更新失败" });
        }
    }
    else
    {
        return BadRequest(ModelState);
    }
}

// 删除部门  
[HttpDelete("DeleteDepartment")]
public async Task<IActionResult> DeleteDepartment(int id)
{
    int result = await _repository.DeleteById(id);
    if (result!=0)
    {
        return Ok(new { message = "部门删除成功" });
    }
    else
    {
        return NotFound(new { message = "未找到要删除的部门" });
    }
}
[HttpGet("GetDepartment")]
public async Task<IActionResult> GetDepartment(int id)
{
    DepartmentModel department = await _repository.GetById(id);
    if (department != null)
    {
        // 将DepartmentModel转换为DepartmentDto,这里只是一个简单的示例  
        //var departmentDto = new DepartmentDto { DepartMentId = department.DepartMentId };
        return Ok(department);
    }
    else
    {
        return NotFound(new { message = "未找到要获取的部门" });
    }
}
// 获取所有部门  
[HttpGet("GetAllDepartments")]
public async Task<IActionResult> GetAllDepartments()
{
    List<DepartmentModel> departments = await _repository.GetAll();
    return Ok(departments);
}

官方网站:
果糖网: https://www.donet5.com/
这只是基础的使用,后续我也会发进阶用法,小伙伴们自己研究吧!加油、未来可期

posted @ 2024-06-13 10:28  北落师门、  阅读(251)  评论(0编辑  收藏  举报