Demo2_Updateable.cs 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. using SqlSugar;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Data;
  5. using Uninpho.DBOperation.Model;
  6. namespace Uninpho.DBOperation.Operation
  7. {
  8. public class Demo2_Updateable
  9. {
  10. public static void Test()
  11. {
  12. SqlSugarClient db = Config.GetPgClient();
  13. /*** 1.entity or List ***/
  14. var updateObj = new User() { Id = 1, Name = "order1" };
  15. var updateObjs = new List<User> {
  16. new User() { Id = 11, Name = "order11" },
  17. new User() { Id = 12, Name = "order12" }
  18. };
  19. //update all columns by primary key
  20. var result = db.Updateable(updateObj).ExecuteCommand();//update single
  21. var result2 = db.Updateable(updateObjs).ExecuteCommand();//update List<Class>
  22. //If there is no primary key
  23. var result5 = db.Updateable(updateObj).WhereColumns(it => new { it.Id }).ExecuteCommand();//update single by id
  24. var result6 = db.Updateable(updateObjs).WhereColumns(it => new { it.Id }).ExecuteCommand();//update List<Class> by id
  25. /*** 2.by expression ***/
  26. //update name,createtime
  27. var result7 = db.Updateable<User>(it => new User() { Name = "a" }).Where(it => it.Id == 11).ExecuteCommand();
  28. var result71 = db.Updateable<User>().SetColumns(it => new User() { Name = "a" }).Where(it => it.Id == 11).ExecuteCommand();
  29. //only update name
  30. var result8 = db.Updateable<User>(it => it.Name == "Name").Where(it => it.Id == 1).ExecuteCommand();
  31. var result81 = db.Updateable<User>()
  32. .SetColumns(it => it.Name == "Name" )
  33. .Where(it => it.Id == 1).ExecuteCommand();
  34. //
  35. /*** 3.by Dictionary ***/
  36. var dt = new Dictionary<string, object>();
  37. dt.Add("id", 1);
  38. dt.Add("name", "abc");
  39. dt.Add("createTime", DateTime.Now);
  40. var dtList = new List<Dictionary<string, object>>();
  41. dtList.Add(dt);
  42. var t66 = db.Updateable(dt).AS("order").WhereColumns("id").ExecuteCommand();
  43. var t666 = db.Updateable(dtList).AS("order").WhereColumns("id").ExecuteCommand();
  44. /*** 4.Other instructions ***/
  45. var caseValue = "1";
  46. //Do not update NULL columns
  47. db.Updateable(updateObj).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommand();
  48. //if 1 update name else if 2 update name,createtime
  49. db.Updateable(updateObj)
  50. .UpdateColumnsIF(caseValue == "1", it => new { it.Name })
  51. .UpdateColumnsIF(caseValue == "2", it => new { it.Name })
  52. .ExecuteCommand();
  53. //Use Lock
  54. db.Updateable(updateObj).With(SqlWith.UpdLock).ExecuteCommand();
  55. //Where Sql
  56. //db.Updateable(updateObj).Where("id=@x", new { x = 1 }).ExecuteCommand();
  57. Console.WriteLine("#### Updateable End ####");
  58. }
  59. }
  60. }