Skip to content
果糖网 edited this page Jul 2, 2024 · 1 revision

1.Update object

1.1 entity or List

//update all columns by primary key
var result= db.Updateable(updateObj).ExecuteCommand();//update single
var result= db.Updateable(updateObjs).ExecuteCommand();//update List<Class>

//Ignore  Name and TestId
var result=db.Updateable(updateObj).IgnoreColumns(it => new { it.CreateTime,it.TestId }).ExecuteCommand()

//only update Name and CreateTime 
var result=db.Updateable(updateObj).UpdateColumns(it => new { it.Name,it.CreateTime }).ExecuteCommand();

//If there is no primary key
var result= db.Updateable(updateObj).WhereColumns(it=>new { it.Id}).ExecuteCommand();//update single by id
var result= db.Updateable(updateObjs).WhereColumns(it=>new { it.Id}).ExecuteCommand();//update List<Class> by id

1.2 by expression

//update  name,createtime
var result= db.Updateable<Student>().SetColumns(it => new Student() { Name = "a", CreateTime = DateTime.Now }).Where(it => it.Id == 11).ExecuteCommand();
//only update name where id=1
var result= db.Updateable<Student>().SetColumns(it => it.Name == "jack").Where(it => it.Id == 1).ExecuteCommand();

1.3 by Dictionary

var dt = new Dictionary<string, object>();
            dt.Add("id", 1);
            dt.Add("name", null);
            dt.Add("createTime", DateTime.Now);
            var t66 = db.Updateable(dt).AS("student").WhereColumns("id").With(SqlWith.UpdLock).ExecuteCommand();

var dtList = new List<Dictionary<string, object>>();
dtList.Add(dt);
dtList.Add(dt2);
var t666 = db.Updateable(dtList).AS("student").WhereColumns("id").With(SqlWith.UpdLock).ExecuteCommand();

2.Other instructions

1.Easy

//Do not update NULL columns
db.Updateable(updateObj).IgnoreNullColumns().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, it.CreateTime })
                .ExecuteCommand(); 
//Use Lock
db.Updateable(updateObj).With(SqlWith.UpdLock).ExecuteCommand();

//Where Sql
db.Updateable(updateObj).Where("id=@x", new { x = "1" }).ExecuteCommand();

//update by subquery
db.Updateable<Student>(entity)
                .Where(p => p.SchoolId == SqlFunc.Subqueryable<Student>().Where(s => s.SchoolId == p.Id).Select(s => s.Id)).ExecuteCommand();