当前位置:   article > 正文

SqlSugar 基础知识_sugarcolumn

sugarcolumn




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

  1. [SugarTable("base_student")]
  2. public class Student
  3. {
  4. /// <summary>
  5. /// IsPrimaryKey 标识是否为主键
  6. /// IsIdentity 是否为自增长
  7. /// </summary>
  8. [SugarColumn(IsPrimaryKey = true, IsIdentity = true, ColumnName = "id")]
  9. public string Id { get; set; }
  10. /// <summary>
  11. /// 定义别名进来Mapping,对应数据库表里面的Remark列
  12. /// </summary>
  13. [SugarColumn(ColumnName = "student_name", ColumnDescription = "用户名")]
  14. public string Name { get; set; }
  15. /// <summary>
  16. /// IsIgnore 不做数据库操作,true将不会进行查询、添加等操作
  17. /// </summary>
  18. [SugarColumn(ColumnName = "created_time", IsIgnore = true, ColumnDescription = "创建时间")]
  19. public DateTime CreatedTime { get; set; } //这列在ORM会过滤掉
  20. }

2、联合查询(一)

  1. public List<MenuDo> GetListByRoleId(string roleId, string sid)
  2. {
  3. var result = Context.db.Queryable<RoleMenuDo, MenuDo>((rm, m) => new object[]
  4. {
  5. JoinType.Left, rm.MenuId ==m.Id
  6. })
  7. .Where((rm, m) => rm.RoleId == roleId && rm.MenuType == 1
  8. && rm.Status != "D" && rm.SchoolId == sid
  9. && m.Status != "D" && m.SchoolId == sid)
  10. .OrderBy((rm, m) => m.Sort, OrderByType.Desc)
  11. .Select((rm, m) => new
  12. {
  13. Id = m.Id,
  14. MenuName = m.MenuName,
  15. ControllerName = m.ControllerName,
  16. ActionName = m.ActionName,
  17. Url = m.Url,
  18. ParentId = m.ParentId,
  19. Sort = m.Sort,
  20. Icon = m.Icon,
  21. }).ToList()
  22. .Select(x => new MenuDo
  23. {
  24. Id = x.Id,
  25. //MenuType = item.MenuType,
  26. MenuName = x.MenuName,
  27. ControllerName = x.ControllerName,
  28. ActionName = x.ActionName,
  29. Url = x.Url,
  30. Icon = x.Icon,
  31. ParentId = x.ParentId,
  32. }).ToList();
  33. return result;
  34. }

3、联合查询(二)

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

4、联合查询 - 简化

  1. public Equipment GetModelByID(string id, string sid)
  2. {
  3. var result = Context.db.Queryable<Equipment, Dormitory>((e, d) => e.DormitoryId == d.Id)
  4. .Where((e, d) => e.SchoolId == sid && e.Status != "D" && d.SchoolId == sid && d.Status != "D")
  5. .Select((e, d) => new Equipment
  6. {
  7. Id = e.Id,
  8. EquipmentCode = e.EquipmentCode,
  9. EquipmentName = e.EquipmentName,
  10. Location = e.Location,
  11. DormitoryId = e.DormitoryId,
  12. DormitoryName = d.DormitoryName,
  13. Mac = e.Mac,
  14. Ip = e.Ip,
  15. InOutType = e.InOutType,
  16. Describe = e.Describe,
  17. Sort = e.Sort,
  18. }).First();
  19. return Mapper.Map<Equipment>(result);
  20. }
  21. //2表查询
  22. var list5 = db.Queryable<Student, School>((st, sc) => st.SchoolId == sc.Id).Select((st,sc)=>new {st.Name,st.Id,schoolName=sc.Name}).ToList();
  23. //3表查询
  24. var list6 = db.Queryable<Student, School,School>((st, sc,sc2) => st.SchoolId == sc.Id&&sc.Id==sc2.Id)
  25. .Select((st, sc,sc2) => new { st.Name, st.Id, schoolName = sc.Name,schoolName2=sc2.Name }).ToList();
  26. //3表查询分页
  27. var list7= db.Queryable<Student, School, School>((st, sc, sc2) => st.SchoolId == sc.Id && sc.Id == sc2.Id)
  28. .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条件查询

  1. var query = Context.SqlQueryable<StudentDto>(sql)
  2. .Where(x => x.Status != "D")
  3. .Where(x => grades.Select(g => new { GradeId = g.Id }).JoinAsString(",").Contains(x.GradeId)
  4. && classes.Select(c => new { ClassId = c.Id }).JoinAsString(",").Contains(x.ClassId))
  5. .WhereIF(request.SchoolId.HasValue(), x => x.SchoolId == request.SchoolId)
  6. .WhereIF(request.ClassId.HasValue(), x => x.ClassId == request.ClassId)
  7. .WhereIF(request.GradeId.HasValue(), x => x.GradeId == request.GradeId)
  8. .WhereIF(request.Search.HasValue(), x => x.StudentName == request.Search || x.StudentCode== request.Search)
  9. .WhereIF(request.NameOrCode.HasValue(),
  10. 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 新增 批量插入

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

7、Update 修改

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

8、删除

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

9、MySQL 存储过程

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

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

  1. var result = Context.db.Ado.UseTran(() =>
  2. {
  3. #region
  4. //Context.db.Deleteable<GradeDo>(x => x.SchoolId == grades[0].SchoolId).ExecuteCommand();
  5. //Context.db.Deleteable<ClassDo>(x => x.SchoolId == grades[0].SchoolId).ExecuteCommand();
  6. #endregion
  7. #region 执行存储过程删除
  8. Context.db.Ado.UseStoredProcedure().GetDataTable("proc_data_delete", new { sid = grades[0].SchoolId });
  9. #endregion
  10. if (grades != null && grades.Count > 0)
  11. Context.db.Insertable(grades.ToArray()).ExecuteCommand();
  12. if (classes != null && classes.Count > 0)
  13. Context.db.Insertable(classes.ToArray()).ExecuteCommand();
  14. });
  15. // result.ErrorException
  16. // result.IsSuccess

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

  1. var result2 = db.Ado.UseTran<List<Student>>(() =>
  2. {
  3. return db.Queryable<Student>().ToList();
  4. });
  5. // result.ErrorException
  6. // result.IsSuccess
  7. // result.Data

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

  1. try
  2. {
  3. Context.db.Ado.BeginTran();
  4. #region 方式1
  5. //Context.db.Deleteable<GradeDo>(x => x.SchoolId == grades[0].SchoolId).ExecuteCommand();
  6. //Context.db.Deleteable<ClassDo>(x => x.SchoolId == grades[0].SchoolId).ExecuteCommand();
  7. #endregion
  8. #region 执行存储过程删除
  9. Context.db.Ado.UseStoredProcedure().GetDataTable("proc_data_delete", new { sid = grades[0].SchoolId });
  10. #endregion
  11. if (grades != null && grades.Count > 0)
  12. Context.db.Insertable(grades.ToArray()).ExecuteCommand();
  13. if (classes != null && classes.Count > 0)
  14. Context.db.Insertable(classes.ToArray()).ExecuteCommand();
  15. if (dormitorys != null && dormitorys.Count > 0)
  16. Context.db.Insertable(dormitorys.ToArray()).ExecuteCommand();
  17. Context.db.Ado.CommitTran();
  18. }
  19. catch (Exception)
  20. {
  21. Context.db.Ado.RollbackTran();
  22. throw;
  23. }
  24. return true;

11、排序

  1. db.Queryable<teacher>().OrderBy("sort desc")
  2. db.Queryable<teacher>()
  3. .OrderBy(it => it.Id) //asc
  4. .OrderBy(it => it.Name, OrderByType.Desc) //desc
  5. .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()
0、

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/134837
推荐阅读
相关标签
  

闽ICP备14008679号