You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

75 lines
2.9 KiB

2 years ago
  1. using OrmTest.Models;
  2. using SqlSugar;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. namespace OrmTest.Demo
  9. {
  10. public class Update : DemoBase
  11. {
  12. public static void Init()
  13. {
  14. var db = GetInstance();
  15. var updateObj = new Student() { Id = 1, Name = "jack", SchoolId = 0, CreateTime = Convert.ToDateTime("2017-05-21 09:56:12.610") };
  16. var updateObjs = new List<Student>() { updateObj, new Student() { Id = 2, Name = "sun", SchoolId = 0 } }.ToArray();
  17. db.IgnoreColumns.Add("TestId", "Student");
  18. //db.MappingColumns.Add("id","dbid", "Student");
  19. //update reutrn Update Count
  20. var t1 = db.Updateable(updateObj).ExecuteCommand();
  21. //Only update Name
  22. var t3 = db.Updateable(updateObj).UpdateColumns(it => new { it.Name }).ExecuteCommand();
  23. var t3_1 = db.Updateable(updateObj).UpdateColumns(it => it == "Name").ExecuteCommand();
  24. //Ignore Name and TestId
  25. var t4 = db.Updateable(updateObj).IgnoreColumns(it => new { it.Name, it.TestId }).ExecuteCommand();
  26. //Ignore Name and TestId
  27. var t5 = db.Updateable(updateObj).IgnoreColumns(it => it == "Name" || it == "TestId").With(SqlWith.UpdLock).ExecuteCommand();
  28. //Use Lock
  29. var t6 = db.Updateable(updateObj).With(SqlWith.UpdLock).ExecuteCommand();
  30. //update List<T>
  31. var t7 = db.Updateable(updateObjs).ExecuteCommand();
  32. //Re Set Value
  33. var t8 = db.Updateable(updateObj)
  34. .ReSetValue(it => it.Name == (it.Name + 1)).ExecuteCommand();
  35. //Where By Expression
  36. var t9 = db.Updateable(updateObj).Where(it => it.Id == 1).ExecuteCommand();
  37. //Update By Expression Where By Expression
  38. var t10 = db.Updateable<Student>()
  39. .UpdateColumns(it => new Student() { Name = "a", CreateTime = DateTime.Now })
  40. .Where(it => it.Id == 11).ExecuteCommand();
  41. //Rename
  42. db.Updateable<School>().AS("Student").UpdateColumns(it => new School() { Name = "jack" }).Where(it => it.Id == 1).ExecuteCommand();
  43. //Update Student set Name='jack' Where Id=1
  44. //Column is null no update
  45. db.Updateable(updateObj).Where(true).ExecuteCommand();
  46. var t12 = db.Updateable<School>().AS("Student").UpdateColumns(it => new School() { Name = "jack" }).Where(it => it.Id == 1).ExecuteCommandAsync();
  47. t12.Wait();
  48. //update one columns
  49. var count = db.Updateable<Student>().UpdateColumns(it => it.SchoolId == it.SchoolId).Where(it => it.Id == it.Id+1).ExecuteCommand();
  50. //update one columns
  51. var count2 = db.Updateable<Student>().UpdateColumns(it => it.SchoolId == it.SchoolId+1).Where(it => it.Id == it.Id + 1).ExecuteCommand();
  52. }
  53. }
  54. }