12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788 |
- using SqlSugar;
- using System;
- using System.Collections.Generic;
- using System.Data;
- using Uninpho.DBOperation.Model;
- namespace Uninpho.DBOperation.Operation
- {
- public class Demo2_Updateable
- {
- public static void Test()
- {
- SqlSugarClient db = Config.GetPgClient();
- /*** 1.entity or List ***/
- var updateObj = new User() { Id = 1, Name = "order1" };
- var updateObjs = new List<User> {
- new User() { Id = 11, Name = "order11" },
- new User() { Id = 12, Name = "order12" }
- };
- //update all columns by primary key
- var result = db.Updateable(updateObj).ExecuteCommand();//update single
- var result2 = db.Updateable(updateObjs).ExecuteCommand();//update List<Class>
-
- //If there is no primary key
- var result5 = db.Updateable(updateObj).WhereColumns(it => new { it.Id }).ExecuteCommand();//update single by id
- var result6 = db.Updateable(updateObjs).WhereColumns(it => new { it.Id }).ExecuteCommand();//update List<Class> by id
- /*** 2.by expression ***/
- //update name,createtime
- var result7 = db.Updateable<User>(it => new User() { Name = "a" }).Where(it => it.Id == 11).ExecuteCommand();
- var result71 = db.Updateable<User>().SetColumns(it => new User() { Name = "a" }).Where(it => it.Id == 11).ExecuteCommand();
- //only update name
- var result8 = db.Updateable<User>(it => it.Name == "Name").Where(it => it.Id == 1).ExecuteCommand();
- var result81 = db.Updateable<User>()
- .SetColumns(it => it.Name == "Name" )
-
- .Where(it => it.Id == 1).ExecuteCommand();
- //
- /*** 3.by Dictionary ***/
- var dt = new Dictionary<string, object>();
- dt.Add("id", 1);
- dt.Add("name", "abc");
- dt.Add("createTime", DateTime.Now);
- var dtList = new List<Dictionary<string, object>>();
- dtList.Add(dt);
- var t66 = db.Updateable(dt).AS("order").WhereColumns("id").ExecuteCommand();
- var t666 = db.Updateable(dtList).AS("order").WhereColumns("id").ExecuteCommand();
- /*** 4.Other instructions ***/
- var caseValue = "1";
- //Do not update NULL columns
- db.Updateable(updateObj).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommand();
- //if 1 update name else if 2 update name,createtime
- db.Updateable(updateObj)
- .UpdateColumnsIF(caseValue == "1", it => new { it.Name })
- .UpdateColumnsIF(caseValue == "2", it => new { it.Name })
- .ExecuteCommand();
- //Use Lock
- db.Updateable(updateObj).With(SqlWith.UpdLock).ExecuteCommand();
- //Where Sql
- //db.Updateable(updateObj).Where("id=@x", new { x = 1 }).ExecuteCommand();
- Console.WriteLine("#### Updateable End ####");
- }
- }
- }
|