Loading

FreeSql (五)插入数据

var connectionString = "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, connectionString)
    .UseAutoSyncStructure(true) //自动同步实体结构到数据库
    .Build(); //请务必定义成 Singleton 单例模式

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.Insert(new Topic { Id = a + 1, Title = $"newtitle0", Clicks = 100 }).ExecuteAffrows();

执行SQL如下:

INSERT INTO `Topic`(`Clicks`, `Title`, `CreateTime`) VALUES(@Clicks0, @Title0, @CreateTime0)

如果表有自增列,插入数据后应该要返回 id。

方法1:(原始)

long id = fsql.Insert(blog).ExecuteIdentity();
blog.Id = id;

方法2:(依赖 FreeSql.Repository)

var repo = fsql.GetRepository<Blog>();
repo.Insert(blog);

内部会将插入后的自增值填充给 blog.Id

插入字典

var dic = new Dictionary<string, object>();
dic.Add("id", 1);
dic.Add("name", "xxxx");

fsql.InsertDict(dic).AsTable("table1").ExecuteAffrows();

API

方法 返回值 参数 描述
CommandTimeout <this> int 命令超时设置(秒)
WithTransaction <this> DbTransaction 设置事务对象
WithConnection <this> DbConnection 设置连接对象
ToSql string 返回即将执行的SQL语句
ExecuteAffrows long 执行SQL语句,返回影响的行数
ExecuteIdentity long 执行SQL语句,返回自增值
ExecuteInserted List<T1> 执行SQL语句,返回插入后的记录
ExecuteSqlBulkCopy void SqlServer 特有的功能,执行 SqlBulkCopy 批量插入的封装
ExecutePgCopy void PostgreSQL 特有的功能,执行 Copy 批量导入数据

系列文章导航

posted @ 2019-09-17 06:25  FreeSql  阅读(13300)  评论(1编辑  收藏  举报