美文网首页.NETdotNET
FreeSql 教程 (十二)更新数据时指定列

FreeSql 教程 (十二)更新数据时指定列

作者: 叶先生_34e6 | 来源:发表于2020-03-13 21:00 被阅读0次

    FreeSql 以 MIT 开源协议托管于 github:https://github.com/2881099/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)
      .ExecuteAffrows();
    //UPDATE `tb_topic` SET `Clicks` = ifnull(`Clicks`,0) + 1 
    //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<T1> 更新数据,设置更新的实体
    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<T1> 传入实体或集合,将其主键作为条件
    WhereExists <this> ISelect 子查询是否存在
    WithTransaction <this> DbTransaction 设置事务对象
    ToSql string 返回即将执行的SQL语句
    ExecuteAffrows long 执行SQL语句,返回影响的行数
    ExecuteUpdated List<T1> 执行SQL语句,返回更新后的记录

    系列文章导航

    相关文章

      网友评论

        本文标题:FreeSql 教程 (十二)更新数据时指定列

        本文链接:https://www.haomeiwen.com/subject/dxjudhtx.html