首页 > 数据库 >SqlSugar 基础知识

SqlSugar 基础知识

时间:2025-01-07 18:23:05浏览次数:1  
标签:SchoolId && db 基础知识 Context new Id SqlSugar

原文链接:https://blog.csdn.net/KingCruel/article/details/98720303

 

 

1、实体特性
[SugarColumn(IsPrimaryKey = true)]  标识是否为主键
[SugarColumn(IsIdentity = true)]  是否为自增长
[SugarColumn(ColumnName = "id")]  对应数据库表里面的某列
[SugarColumn(IsIgnore = true)]  忽略熟悉,在ORM会过滤掉
[SugarColumn(ColumnDescription = "创建时间")]  描述

[SugarTable("base_student")]
public class Student
{
    /// <summary>
    /// IsPrimaryKey 标识是否为主键
    /// IsIdentity 是否为自增长
    /// </summary>
    [SugarColumn(IsPrimaryKey = true, IsIdentity = true, ColumnName = "id")]
    public string Id { get; set; }

    /// <summary>
    /// 定义别名进来Mapping,对应数据库表里面的Remark列
    /// </summary>
    [SugarColumn(ColumnName = "student_name", ColumnDescription = "用户名")]
    public string Name { get; set; }

    /// <summary>
    /// IsIgnore 不做数据库操作,true将不会进行查询、添加等操作
    /// </summary>
    [SugarColumn(ColumnName = "created_time", IsIgnore = true, ColumnDescription = "创建时间")]
    public DateTime CreatedTime { get; set; } //这列在ORM会过滤掉
}

2、联合查询(一)

public List<MenuDo> GetListByRoleId(string roleId, string sid)
{
    var result = Context.db.Queryable<RoleMenuDo, MenuDo>((rm, m) => new object[]
    {
        JoinType.Left, rm.MenuId ==m.Id
    })
    .Where((rm, m) => rm.RoleId == roleId && rm.MenuType == 1
    && rm.Status != "D" && rm.SchoolId == sid
    && m.Status != "D" && m.SchoolId == sid)
    .OrderBy((rm, m) => m.Sort, OrderByType.Desc)
    .Select((rm, m) => new
    {
        Id = m.Id,
        MenuName = m.MenuName,
        ControllerName = m.ControllerName,
        ActionName = m.ActionName,
        Url = m.Url,
        ParentId = m.ParentId,
        Sort = m.Sort,
        Icon = m.Icon,
    }).ToList()
    .Select(x => new MenuDo
    {
        Id = x.Id,
        //MenuType = item.MenuType,
        MenuName = x.MenuName,
        ControllerName = x.ControllerName,
        ActionName = x.ActionName,
        Url = x.Url,
        Icon = x.Icon,
        ParentId = x.ParentId,
    }).ToList();

    return result;
}

3、联合查询(二)

var result1 = Context.db.Queryable<ClassDo, GradeDo>((c, g) => new object[]
                { JoinType.Left, c.GradeId == g.Id })
                .Where((c, g) => c.SchoolId == sid && c.Status != "D" && g.SchoolId == sid && g.Status != "D")
                .WhereIF(string.IsNullOrEmpty(name), (c, g) =>
                    c.ClassName.Contains(name) || c.ClassCode.Contains(name) || g.GradeName.Contains(name) || g.GradeCode.Contains(name))
                .Select<ClassViewModel>().ToPageList(pageIndex, pageSize, ref total);

4、联合查询 - 简化

public Equipment GetModelByID(string id, string sid)
{
    var result = Context.db.Queryable<Equipment, Dormitory>((e, d) => e.DormitoryId == d.Id)
       .Where((e, d) => e.SchoolId == sid && e.Status != "D" && d.SchoolId == sid && d.Status != "D")
       .Select((e, d) => new Equipment
       {
           Id = e.Id,
           EquipmentCode = e.EquipmentCode,
           EquipmentName = e.EquipmentName,
           Location = e.Location,
           DormitoryId = e.DormitoryId,
           DormitoryName = d.DormitoryName,
           Mac = e.Mac,
           Ip = e.Ip,
           InOutType = e.InOutType,
           Describe = e.Describe,
           Sort = e.Sort,
       }).First();
    return Mapper.Map<Equipment>(result);
}

//2表查询
var list5 = db.Queryable<Student, School>((st, sc) => st.SchoolId == sc.Id).Select((st,sc)=>new {st.Name,st.Id,schoolName=sc.Name}).ToList();
 
//3表查询
var list6 = db.Queryable<Student, School,School>((st, sc,sc2) => st.SchoolId == sc.Id&&sc.Id==sc2.Id)
    .Select((st, sc,sc2) => new { st.Name, st.Id, schoolName = sc.Name,schoolName2=sc2.Name }).ToList();
 
//3表查询分页
var list7= db.Queryable<Student, School, School>((st, sc, sc2) => st.SchoolId == sc.Id && sc.Id == sc2.Id)
.Select((st, sc, sc2) => new { st.Name, st.Id, schoolName = sc.Name, schoolName2 = sc2.Name }).ToPageList(1,2);


0、public IHttpActionResult GetAllGrade()
0、public IHttpActionResult GetAllGrade()
5、WHERE条件查询

var query = Context.SqlQueryable<StudentDto>(sql)
            .Where(x => x.Status != "D")
            .Where(x => grades.Select(g => new { GradeId = g.Id }).JoinAsString(",").Contains(x.GradeId)
                    && classes.Select(c => new { ClassId = c.Id }).JoinAsString(",").Contains(x.ClassId))
            .WhereIF(request.SchoolId.HasValue(), x => x.SchoolId == request.SchoolId)
            .WhereIF(request.ClassId.HasValue(), x => x.ClassId == request.ClassId)
            .WhereIF(request.GradeId.HasValue(), x => x.GradeId == request.GradeId)
            .WhereIF(request.Search.HasValue(), x => x.StudentName == request.Search || x.StudentCode== request.Search)
            .WhereIF(request.NameOrCode.HasValue(),
                        x => x.StudentName.Contains(request.NameOrCode) || x.StudentCode.Contains(request.NameOrCode));

Between ... AND ...

db.Queryable<Student>().Where(it => SqlFunc.Between(it.Id, 1, 20)).ToList();

6、Insert 新增 批量插入

var insertData = new course() { };//测试参数
var insertArray = new course[] { insertData };
courseDb.Insert(insertData);//插入
courseDb.InsertRange(insertArray);//批量插入
var id = courseDb.InsertReturnIdentity(insertData);//插入返回自增列
courseDb.AsInsertable(insertData).ExecuteCommand();//我们可以转成 Insertable实现复杂插入
var insertObjs = new List<Student>(); //批量插入
var s9 = db.Insertable(insertObjs.ToArray()).ExecuteCommand();
//注意 : SqlSever 建表语句带有Wtih(设置),如果设置不合理,可能会引起慢,把With删掉就会很快

7、Update 修改

var updateData = new course() {  };//测试参数
var updateArray = new course[] { updateData };//测试参数
courseDb.Update(updateData);//根据实体更新
courseDb.UpdateRange(updateArray);//批量更新
// 只更新Name列和CreateTime列,其它列不更新,条件id=1
//courseDb.Update(it => new course() { Name = "a", CreateTime = DateTime.Now }, it => it.id==1);
courseDb.AsUpdateable(updateData).ExecuteCommand();

8、删除

var deldata = new course() {  };//测试参数
courseDb.Delete(deldata);//根据实体删除
courseDb.DeleteById(1);//根据主键删除
courseDb.DeleteById(new int[] { 1,2});//根据主键数组删除
courseDb.Delete(it=>1==2);//根据条件删除
courseDb.AsDeleteable().Where(it=>1==2).ExecuteCommand();//转成Deleteable实现复杂的操作

9、MySQL 存储过程

-- ----------------------------
-- Procedure structure for delete_data
-- ----------------------------
DROP PROCEDURE IF EXISTS `delete_data`;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `delete_data`(in sid VARCHAR(36))
BEGIN
    DELETE FROM base_grade WHERE school_id=sid;
    DELETE FROM sys_user_info WHERE school_id=sid AND (mobile IS NULL OR mobile != 'admin');
    SET @adminId = '';
    SELECT @adminId := id FROM sys_user_info WHERE school_id=sid AND mobile = 'admin';
    DELETE FROM sys_user_role WHERE school_id=sid and user_id != @adminId;
END;;
DELIMITER ;
//执行存储过程删除
var del = Context.Ado.UseStoredProcedure().GetDataTable("delete_data", new { sid = grades[0].SchoolId });

10、事务
1、无数据返回只返回状态

var result = Context.db.Ado.UseTran(() =>
{
    #region
    //Context.db.Deleteable<GradeDo>(x => x.SchoolId == grades[0].SchoolId).ExecuteCommand();
    //Context.db.Deleteable<ClassDo>(x => x.SchoolId == grades[0].SchoolId).ExecuteCommand();
    #endregion

    #region 执行存储过程删除
    Context.db.Ado.UseStoredProcedure().GetDataTable("proc_data_delete", new { sid = grades[0].SchoolId });
    #endregion

    if (grades != null && grades.Count > 0)
        Context.db.Insertable(grades.ToArray()).ExecuteCommand();

    if (classes != null && classes.Count > 0)
        Context.db.Insertable(classes.ToArray()).ExecuteCommand();
});
// result.ErrorException
// result.IsSuccess

2、返回数据并且返回状态

var result2 = db.Ado.UseTran<List<Student>>(() =>
{
    return db.Queryable<Student>().ToList();
});
// result.ErrorException
// result.IsSuccess
// result.Data

3、使用try catch来处理事务,用这种方式事务一定要加try catch回滚不然会锁表,在操作就卡死

try
{
    Context.db.Ado.BeginTran();

    #region 方式1
    //Context.db.Deleteable<GradeDo>(x => x.SchoolId == grades[0].SchoolId).ExecuteCommand();
    //Context.db.Deleteable<ClassDo>(x => x.SchoolId == grades[0].SchoolId).ExecuteCommand();
    #endregion

    #region 执行存储过程删除
    Context.db.Ado.UseStoredProcedure().GetDataTable("proc_data_delete", new { sid = grades[0].SchoolId });
    #endregion

    if (grades != null && grades.Count > 0)
        Context.db.Insertable(grades.ToArray()).ExecuteCommand();

    if (classes != null && classes.Count > 0)
        Context.db.Insertable(classes.ToArray()).ExecuteCommand();

    if (dormitorys != null && dormitorys.Count > 0)
        Context.db.Insertable(dormitorys.ToArray()).ExecuteCommand();

    Context.db.Ado.CommitTran();
}
catch (Exception)
{
    Context.db.Ado.RollbackTran();
    throw;
}
return true;

11、排序

db.Queryable<teacher>().OrderBy("sort desc")

db.Queryable<teacher>()
.OrderBy(it => it.Id) //asc
.OrderBy(it => it.Name, OrderByType.Desc) //desc
.ToList()

0、public IHttpActionResult GetAllGrade()
0、public IHttpActionResult GetAllGrade()
0、public IHttpActionResult GetAllGrade()
0、public IHttpActionResult GetAllGrade()
0、public IHttpActionResult GetAllGrade()
0、public IHttpActionResult GetAllGrade()
0、public IHttpActionResult GetAllGrade()
0、public IHttpActionResult GetAllGrade()
0、public IHttpActionResult GetAllGrade()
0、public IHttpActionResult GetAllGrade()

标签:SchoolId,&&,db,基础知识,Context,new,Id,SqlSugar
From: https://www.cnblogs.com/Dongmy/p/18658101

相关文章

  • 前端基础知识了解
    前端开发的三要素前端开发的三要素通常指的是HTML、CSS和JavaScript。 HTML(超文本标记语言):HTML是构建网页内容的基础,它使用标签来定义网页的结构和内容,如文本、图像、链接、表格等。例如,<p>标签用于定义段落,<img>标签用于插入图像。 CSS(层叠样式表):CSS用于控制网页的样式......
  • AWS Auto Scaling基础知识
    AutoScaling概念知识点:AutoScaling可根据定义的条件自动扩展或缩减AmazonEC2容量,确保运行适量的EC2实例处理应用程序的流量或负载。关键组件包括AutoScalingGroup(作为一个逻辑组进行扩展的EC2实例集合)、LaunchConfiguration/Template(定义如何在AutoScaling组中启动E......
  • Amazon SQS基础知识
    AmazonSimpleQueueService(SQS)在与云架构中的服务消息收发、排队和解耦相关的主题中发挥着关键作用。知识点:亚马逊SQS是全托管消息队列服务,能让分布式应用或服务间解耦通信。常用于消息缓冲、任务处理、工作负载分配,可应对高吞吐量场景,还具备容错能力。注意事项:理解其......
  • 动手学深度学习-python基础知识介绍(数据处理基础流程)part2
    数据预处理importosos.makedirs(os.path.join('..','data'),exist_ok=True)data_file=os.path.join('..','data','house_tiny.csv')withopen(data_file,'w')asf:f.write('NumRooms,Alley,Price\n&......
  • 动手学深度学习-python基础知识介绍part1
    基础详解-part1importtorchx=torch.arange(12)xx.shapex.numel()#数组中元素的总数#修改形状x.reshape(3,4)torch.zeros((2,3,4))#两层,三行,四列print(torch.tensor([[2,1,4,3],[1,2,3,4],[4,3,2,1]]).shape)#二维#两个框表示二维,三个表示三维print(torch.tens......
  • 基础知识-虚拟化(Virtualization)技术
    (250106)参考资料KVM虚拟化技术|cnblogs|惨绿少年@clsn.io虚拟化介绍|cnblogs|休耕云计算与虚拟化技术发展编年史|cnblogs|云物互联nova系列二:kvm介绍|cnblogs|linhaifeng虚拟化与容器|cnblogs|marility《LPIC-3-Virtualization-and-Containerization-......
  • 前端基础知识:浏览器的进程与线程
    白话文先总结把浏览器想象成一栋楼,每家就是一个进程,家里的每个人就是线程,每个进程有一块独立的区域也就是内存,每个进程可以有多个线程同时工作可以互不干扰。1.什么是进程与线程?进程定义:进程是计算机操作系统中资源分配的最小单位。特点:每个进程有独立的内存空间......
  • 【计算机二级】计算机等级考试公共基础知识——计算机系统
    目录一、计算机的发展二、计算机硬件系统1.中央处理器2.存储器3.输入设备和输出设备4.总线三、信息的表示与存储1.存储单位2.二进制与十进制的转换3.字符编码四、操作系统1.操作系统的发展2.进程管理3.存储管理4.文件管理5.I/O设备管理特别鸣谢......
  • vue3-openlayers基础知识简介
    vue3-openlayers基础知识简介OpenLayers3Primeropenlayers6:入门基础(一)openlayers入门教程一、基础概念介绍地图(Map)OpenLayers的核心部件是Map(ol.Map)。它被呈现到对象target容器(例如,网页上的div元素)。所有地图的属性可以在构造时进行配置。ol/Map类是OpenLayers......
  • tryhackme-Cyber Security 101-Exploitation Basics(漏洞利用基础知识)-Blue(蓝)
    利用常见的错误配置问题,部署并入侵Windows机器。这个房间有个教学视频。可以根据这个视频复现。任务1:侦察按下面的 启动机器 按钮。按此页面顶部的 StartAttackBox按钮启动AttackBox。AttackBox机器将在分屏视图中启动。如果它不可见,请使用页面顶部的蓝色 Show......