FreeSql (十二)更新數據時指定列


var connstr = "Data Source=127.0.0.1;Port=3306;User ID=root;Password=root;" + 
    "Initial Catalog=cccddd;Charset=utf8;SslMode=none;Max pool size=10";

static IFreeSql fsql = new FreeSql.FreeSqlBuilder()
    .UseConnectionString(FreeSql.DataType.MySql, connstr)
    .UseAutoSyncStructure(true) //自動同步實體結構到數據庫
    .Build(); //請務必定義成 Singleton 單例模式

[Table(Name = "tb_topic")]
class Topic {
    [Column(IsIdentity = true, IsPrimary = true)]
    public int Id { get; set; }
    public int Clicks { get; set; }
    public string Title { get; set; }
    public DateTime CreateTime { get; set; }
}

更新指定列

fsql.Update<Topic>(1)
  .Set(a => a.CreateTime, DateTime.Now)
  .ExecuteAffrows();
//UPDATE `tb_topic` SET `CreateTime` = '2018-12-08 00:04:59' 
//WHERE (`Id` = 1)

支持 Set() 多次,相當於拼接

更新指定列,累加

fsql.Update<Topic>(1)
  .Set(a => a.Clicks + 1)
  .Set(a => a.Time == DateTime.Now)
  .ExecuteAffrows();
//UPDATE `tb_topic` SET `Clicks` = ifnull(`Clicks`,0) + 1, `Time` = now() 
//WHERE (`Id` = 1)

更新指定列,一次指定

fsql.Update<Topic>(1).Set(a => new Topic
  {
    Clicks = a.Clicks + 1,
    Time = DateTime.Now
  })
  .ExecuteAffrows();
//UPDATE `tb_topic` SET `Clicks` = `Clicks` + 1, `Time` = now() 
//WHERE (`Id` = 1)

根據 Dto 更新

fsql.Update<T>()
  .SetDto(new { title = "xxx", clicks = 2 })
  .Where(a => a.Id == 1)
  .ExecuteAffrows();
//UPDATE `tb_topic` SET `Title` = ?p_0, `Clicks` = ?p_1
//WHERE (Id = 1)

fsql.Update<T>()
  .SetDto(new Dictionary<string, object> { ["title"] = "xxx", ["clicks"] = 2 })
  .Where(a => a.Id == 1)
  .ExecuteAffrows();
//效果同上

自定義SQL

fsql.Update<Topic>()
  .SetRaw("Title = @title", new { title = "新標題" })
  .Where("Id = @id", 1)
  .ExecuteAffrows();
//UPDATE `tb_topic` SET Title = @title WHERE (Id = @id)

API

方法 返回值 參數 描述
SetSource <this> T1 | IEnumerable 更新數據,設置更新的實體
Set <this> Lambda, value 設置列的新值,Set(a => a.Name, "newvalue")
Set <this> Lambda 設置列的的新值為基礎上增加,Set(a => a.Clicks + 1),相當於 clicks=clicks+1
SetDto <this> object 根據 dto 更新的方法
SetRaw <this> string, parms 設置值,自定義SQL語法,SetRaw("title = ?title", new { title = "newtitle" })
Where <this> Lambda 表達式條件,僅支持實體基礎成員(不包含導航對象)
Where <this> string, parms 原生sql語法條件,Where("id = ?id", new { id = 1 })
Where <this> T1 | IEnumerable 傳入實體或集合,將其主鍵作為條件
WhereExists <this> ISelect 子查詢是否存在
WithTransaction <this> DbTransaction 設置事務對象
ToSql string 返回即將執行的SQL語句
ExecuteAffrows long 執行SQL語句,返回影響的行數
ExecuteUpdated List<T1> 執行SQL語句,返回更新后的記錄

系列文章導航


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM