刪除是一個很是危險的操做,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語句,返回被刪除的記錄 |