一、前言 SqlSugar從去年到現在已經一年了,版本從1.0升到了現在的2.3 ,這是一個穩定版本 ,有數家公司已經項目上線,在這裡我將SqlSugar的功能重新整理成一篇新的貼子,希望大家喜歡。 公司團隊項目、產品已經完全拋棄EF,SqlSugar定位不是ORM,而是為了方便的讓你去寫Sql。 ...
一、前言
SqlSugar從去年到現在已經一年了,版本從1.0升到了現在的2.3 ,這是一個穩定版本 ,有數家公司已經項目上線,在這裡我將SqlSugar的功能重新整理成一篇新的貼子,希望大家喜歡。
公司團隊項目、產品已經完全拋棄EF,SqlSugar定位不是ORM,而是為了方便的讓你去寫Sql。
媲美原生ADO.NET的性能、簡潔的語法和支持Json 、Dynamic、 List<T>、 List<string[]>、 ValueType和 Dictionary 等多種類型的返回值 有很多亮點。
執行十萬次【拉姆達】轉成【Sql】只用了1秒多(機型:Surface Pro4 I5 8G)
與其他框架的性能測試(機型:過時機器)
二、功能介紹
查詢
1、SqlQuery 用於執行原生SQL和存儲過程
//轉成list List<Student> list1 = db.SqlQuery<Student>("select * from Student"); //轉成list帶參 List<Student> list2 = db.SqlQuery<Student>("select * from Student where id=@id", new { id = 1 }); //轉成dynamic dynamic list3 = db.SqlQueryDynamic("select * from student"); //轉成json string list4 = db.SqlQueryJson("select * from student"); //返回int var list5 = db.SqlQuery<int>("select top 1 id from Student").Single(); //反回鍵值 Dictionary<string, string> list6 = db.SqlQuery<KeyValuePair<string, string>>("select id,name from Student").ToDictionary(it => it.Key, it => it.Value); //反回List<string[]> var list7 = db.SqlQuery<string[]>("select top 1 id,name from Student").Single(); //存儲過程 var spResult = db.SqlQuery<School>("exec sp_school @p1,@p2", new { p1=1,p2=2 });Sql查詢
2、Queryable 用於單表或者視圖查詢
//---------Queryable<T>,擴展函數查詢---------// //針對單表或者視圖查詢 //查詢所有 var student = db.Queryable<Student>().ToList(); var studentDynamic = db.Queryable<Student>().ToDynamic(); var studentJson = db.Queryable<Student>().ToJson(); //查詢單條 var single = db.Queryable<Student>().Single(c => c.id == 1); //查詢單條沒有記錄返回空對象 var single2 = db.Queryable<Student>().Where(c => c.id == 1).SingleOrDefault(); //查詢第一條 var first = db.Queryable<Student>().Where(c => c.id == 1).First(); var first2 = db.Queryable<Student>().Where(c => c.id == 1).FirstOrDefault(); //取10-20條 var page1 = db.Queryable<Student>().Where(c => c.id > 10).OrderBy("id").Skip(10).Take(20).ToList(); //上一句的簡化寫法,同樣取10-20條 var page2 = db.Queryable<Student>().Where(c => c.id > 10).OrderBy("id").ToPageList(2, 10); //查詢條數 var count = db.Queryable<Student>().Where(c => c.id > 10).Count(); //從第2條開始以後取所有 var skip = db.Queryable<Student>().Where(c => c.id > 10).OrderBy("id").Skip(2).ToList(); //取前2條 var take = db.Queryable<Student>().Where(c => c.id > 10).OrderBy("id").Take(2).ToList(); // Not like string conval = "a"; var notLike = db.Queryable<Student>().Where(c => !c.name.Contains(conval.ToString())).ToList(); // 可以在拉姆達使用 ToString和 Convert,比EF出色的地方 var convert1 = db.Queryable<Student>().Where(c => c.name == "a".ToString()).ToList(); var convert2 = db.Queryable<Student>().Where(c => c.id == Convert.ToInt32("1")).ToList();// var convert3 = db.Queryable<Student>().Where(c => DateTime.Now > Convert.ToDateTime("2015-1-1")).ToList(); var convert4 = db.Queryable<Student>().Where(c => DateTime.Now > DateTime.Now).ToList(); //支持字元串Where 讓你解決,更複雜的查詢 var student12 = db.Queryable<Student>().Where(c => "a" == "a").Where("id>100").ToList(); var student13 = db.Queryable<Student>().Where(c => "a" == "a").Where("id>100 and id in( select 1)").ToList(); //存在記錄反回true,則否返回false bool isAny100 = db.Queryable<Student>().Any(c => c.id == 100); bool isAny1 = db.Queryable<Student>().Any(c => c.id == 1); int maxId = db.Queryable<Student>().Max<Student, int>("id"); int minId = db.Queryable<Student>().Where(c => c.id > 0).Min<Student, int>("id"); //In var list1= db.Queryable<Student>().In("id", "1", "2", "3").ToList(); var list2=db.Queryable<Student>().In("id", new string[] { "1", "2", "3" }).ToList(); var list3=db.Queryable<Student>().In("id", new List<string> { "1", "2", "3" }).ToList(); var list4 = db.Queryable<Student>().Where(it=>it.id<10).In("id", new List<string> { "1", "2", "3" }).ToList(); //分組查詢 var list5= db.Queryable<Student>().Where(c => c.id < 20).GroupBy("sex").Select<Student, SexTotal>("Sex,Count=count(*)").ToList(); //SELECT Sex,Count=count(*) FROM Student WHERE 1=1 AND (id < 20) GROUP BY Sex --生成結果單表查詢
3、Sqlable 用於多表查詢
//---------Sqlable,創建多表查詢---------// //多表查詢 List<School> dataList = db.Sqlable() .From("school", "s") .Join("student", "st", "st.id", "s.id", JoinType.INNER) .Join("student", "st2", "st2.id", "st.id", JoinType.LEFT) .Where("s.id>100 and s.id<@id") .Where("1=1")//可以多個WHERE .SelectToList<School/*新的Model我這裡沒有所以寫的School*/>("st.*", new { id = 1 }); //多表分頁 List<School> dataPageList = db.Sqlable() .From("school", "s") .Join("student", "st", "st.id", "s.id", JoinType.INNER) .Join("student", "st2", "st2.id", "st.id", JoinType.LEFT) .Where("s.id>100 and s.id<100") .SelectToPageList<School>("st.*", "s.id", 1, 10); //多表分頁WHERE加子查詢 List<School> dataPageList2 = db.Sqlable() .From("school", "s") .Join("student", "st", "st.id", "s.id", JoinType.INNER) .Join("student", "st2", "st2.id", "st.id", JoinType.LEFT) .Where("s.id>100 and s.id<100 and s.id in (select 1 )" /*這裡面寫子查詢都可以*/) .SelectToPageList<School>("st.*", "s.id", 1, 10); //--------轉成List Dynmaic 或者 Json-----// //不分頁 var list1 = db.Sqlable().From("student", "s").Join("school", "l", "s.sch_id", "l.id and l.id=@id", JoinType.INNER).SelectToDynamic("*", new { id = 1 }); var list2 = db.Sqlable().From("student", "s").Join("school", "l", "s.sch_id", "l.id and l.id=@id", JoinType.INNER).SelectToJson("*", new { id = 1 }); var list3 = db.Sqlable().From("student", "s").Join("school", "l", "s.sch_id", "l.id and l.id=@id", JoinType.INNER).SelectToDataTable("*", new { id = 1 }); //分頁 var list4 = db.Sqlable().From("student", "s").Join("school", "l", "s.sch_id", "l.id and l.id=@id", JoinType.INNER).SelectToPageDynamic("s.*", "l.id", 1, 10, new { id = 1 }); var list5 = db.Sqlable().From("student", "s").Join("school", "l", "s.sch_id", "l.id and l.id=@id", JoinType.INNER).SelectToPageTable("s.*", "l.id", 1, 10, new { id = 1 }); var list6 = db.Sqlable().From("student", "s").Join("school", "l", "s.sch_id", "l.id and l.id=@id", JoinType.INNER).SelectToPageDynamic("s.*", "l.id", 1, 10, new { id = 1 }); //--------拼接-----// Sqlable sable = db.Sqlable().From<Student>("s").Join<School>("l", "s.sch_id", "l.id", JoinType.INNER); string name = "a"; int id = 1; if (!string.IsNullOrEmpty(name)) { sable = sable.Where("s.name=@name"); } if (!string.IsNullOrEmpty(name)) { sable = sable.Where("s.id=@id or s.id=100"); } if (id > 0) { sable = sable.Where("l.id in (select top 10 id from school)");//where加子查詢 } var pars = new { id = id, name = name }; int pageCount = sable.Count(pars); var list7 = sable.SelectToPageList<Student>("s.*","l.id desc",1,20, pars);多表查詢
4、新容器轉換
using (SqlSugarClient db = SugarDao.GetInstance()) { var list2= db.Queryable<Student>().Where(c => c.id < 10).Select(c => new classNew { newid = c.id, newname = c.name, xx_name = c.name }).ToList();//不支持匿名類轉換,也不建議使用 var list3 = db.Queryable<Student>().Where(c => c.id < 10).Select(c => new { newid = c.id, newname = c.name, xx_name = c.name }).ToDynamic();//匿名類轉換 }新容器轉換
添加
using (SqlSugarClient db = SugarDao.GetInstance())//開啟資料庫連接 { Student s = new Student() { name = "張" + new Random().Next(1, int.MaxValue) }; db.Insert(s); //插入一條記錄 (有主鍵也好,沒主鍵也好,有自增列也好都可以插進去) List<Student> list = new List<Student>() { new Student() { name="張"+new Random().Next(1,int.MaxValue) }, new Student() { name="張"+new Random().Next(1,int.MaxValue) } }; db.InsertRange(list); //批量插入 } }添加
更新
using (var db = SugarDao.GetInstance()) { //指定列更新 db.Update<School>(new { name = "藍翔2" }, it => it.id == id); db.Update<School, int>(new { name = "藍翔2" }, 1, 3, 12); db.Update<School, string>(new { name = "藍翔2" }, new string[] { "1", "2" }); //整個實體更新 db.Update(new School { id = id, name = "藍翔2" }); db.Update<School>(new School { id = id, name = "藍翔2" }, it => it.id == id); //設置不更新列 db.DisableUpdateColumns = new string[] { "CreateTime" };//設置CreateTime不更新 TestUpdateColumns updObj = new TestUpdateColumns() { VGUID = Guid.Parse("542b5a27-6984-47c7-a8ee-359e483c8470"), Name = "xx", Name2 = "xx2", IdentityField = 0, CreateTime = null }; //CreateTime將不會被更新 db.Update(updObj); //以前實現這種更新需要用指定列的方式實現,現在就簡單多了。 }更新
刪除和假刪除
using (var db = SugarDao.GetInstance()) { //真刪除 db.Delete<School, int>(10);//註意主鍵必需為實體類的第一個屬性 db.Delete<School>(it => it.id > 100); db.Delete<School, string>(new string[] { "100", "101", "102" }); //假刪除 //db.FalseDelete<school>("is_del", 100); //等同於 update school set is_del=0 where id in(100) //db.FalseDelete<school>("is_del", it=>it.id==100); }刪除
全局過濾器
這功能主要用於通用許可權設計等功能, 當有很多WHERE重覆,並且動態 這時候就需要在全局設置好過濾器介面集合,程式中使用只需要設KEY便可
/// <summary> /// 過濾器 /// </summary> public partial class Filter : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { using (SqlSugarClient db = SugarDaoFilter.GetInstance())//開啟資料庫連接 { //設置走哪個過濾器 db.CurrentFilterKey = "role"; //queryable var list = db.Queryable<Student>().ToList(); //通過全局過濾器對需要許可權驗證的數據進行過濾 //相當於db.Queryable<Student>().Where("id=@id",new{id=1}) //sqlable var list2 = db.Sqlable().Form<Student>("s").SelectToList<Student>("*"); //同上 //sqlQuery var list3 = db.SqlQuery<Student>("select * from Student"); //同上 } } } /// <summary> /// 擴展SqlSugarClient /// </summary> public class SugarDaoFilter { //禁止實例化 private SugarDaoFilter() { } /// <summary> /// 頁面所需要的過濾函數 /// </summary> private static Dictionary<string, Func<KeyValueObj>> _filterParas = new Dictionary<string, Func<KeyValueObj>>() { { "role",()=>{ return new KeyValueObj(){ Key=" id=@id" , Value=new{ id=1}}; } }, { "org",()=>{ return new KeyValueObj(){ Key=" orgId=@orgId" , Value=new{ orgId=1}}; } }, }; public static SqlSugarClient GetInstance() { string connection = System.Configuration.ConfigurationManager.ConnectionStrings[@"sqlConn"].ToString(); //這裡可以動態根據cookies或session實現多庫切換 var reval = new SqlSugarClient(connection); reval.SetFilterFilterParas(_filterParas); return reval; } }過濾器
無參模式
將IsGetPageParas設為true之後頁面的參數都不需要使用 new{}來賦值
using (SqlSugarClient db = SugarDao.GetInstance())//開啟資料庫連接 { db.IsGetPageParas = true;//使用無參模式直接將Requst中的ID傳給@id無需在代碼中寫出來 var list = db.Queryable<Student>().Where("id=@id").ToList(); //sqlable queryable sqlquery通用 //獲取頁面所有參數到鍵值對 //var kvs= SqlSugarTool.GetParameterDictionary(); //以前寫法 //var xx = db.Queryable<Student>().Where("id=@id", new { id=Request["id"] }).ToList(); }無參
事務
using (SqlSugarClient db = SugarDao.GetInstance())//開啟資料庫連接 { db.IsNoLock = true;//啟用無鎖查詢 db.CommandTimeOut = 30000;//設置超時時間 try { db.BeginTran();//開啟事務 db.CommitTran();//提交事務 } catch (Exception) { db.RollbackTran();//回滾事務 throw; } }事務
公開函數
//ToJoinSqlInVal var par = new string[] { "a", "c", "3" }; var ids = par.ToJoinSqlInVal();//將數組轉成 'a','c','3' 有防SQL註入處理 //ToSqlValue try { var par2 = "a'"; var newpar2 = par2.ToSqlValue();//對字元串防註入處理 } catch (Exception ex) { Response.Write(ex.Message); } //SqlLikeWordEncode 處理LIKE特殊字元 var likestr = SqlSugarTool.SqlLikeWordEncode("[%%%