删除是一个很是危险的操做,FreeSql对删除支持并不强大,仅支持了单表有条件的删除方法。html
不想过多的介绍拉长删除数据的系列文章,删除数据的介绍仅此一篇。sql
若Where条件为空的时候执行方法,FreeSql仅返回0或默认值,不执行真正的SQL删除操做。数据库
为了加强系统的安全性,强烈建议在实体中增长 is_deledted 字段作软删除标识。api
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"; IFreeSql fsql = new FreeSql.FreeSqlBuilder() .UseConnectionString(FreeSql.DataType.MySql, connstr) .UseAutoSyncStructure(true) //自动同步实体结构到数据库 .Build(); [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; } }
Delete<Topic>(object dywhere)
dywhere 支持安全
fsql.Delete<Topic>(new[] { 1, 2 }).ExecuteAffrows(); //DELETE FROM `tb_topic` WHERE (`Id` = 1 OR `Id` = 2) fsql.Delete<Topic>(new Topic { Id = 1, Title = "test" }).ExecuteAffrows(); //DELETE FROM `tb_topic` WHERE (`Id` = 1) fsql.Delete<Topic>(new[] { new Topic { Id = 1, Title = "test" }, new Topic { Id = 2, Title = "test" } }).ExecuteAffrows(); //DELETE FROM `tb_topic` WHERE (`Id` = 1 OR `Id` = 2) fsql.Delete<Topic>(new { id = 1 }).ExecuteAffrows(); //DELETE FROM `tb_topic` WHERE (`Id` = 1)
出于安全考虑,没有条件不执行删除动做,避免误删除全表数据
删除全表数据:fsql.Delete<T>().Where("1=1").ExecuteAffrows()ui
fsql.Delete<Topic>().Where(a => a.Id == 1).ExecuteAffrows(); //DELETE FROM `tb_topic` WHERE (`Id` = 1) fsql.Delete<Topic>().Where("id = ?id", new { id = 1 }).ExecuteAffrows(); //DELETE FROM `tb_topic` WHERE (id = ?id) var item = new Topic { Id = 1, Title = "newtitle" }; fsql.Delete<Topic>().Where(item).ExecuteAffrows(); //DELETE FROM `tb_topic` WHERE (`Id` = 1) var items = new List<Topic>(); for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 }); fsql.Delete<Topic>().Where(items).ExecuteAffrows(); //DELETE FROM `tb_topic` WHERE (`Id` IN (1,2,3,4,5,6,7,8,9,10))
方法 | 返回值 | 参数 | 描述 |
---|---|---|---|
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语句,返回影响的行数 | |
ExecuteDeleted | List<T1> | 执行SQL语句,返回被删除的记录 |