sqlsugar Mapper功能


Mapper功能

如果說 .Select() 也可以實現一對一的查詢或者一些SQL函數但是畢竟是用來生成SQL的所以有很多局限性,Mapper是在查詢出結果后進行處理所以任何C#方法都支持

也更強大

復制代碼
 var s12 = db.Queryable<Student, School>((st, sc) => st.SchoolId == sc.Id).Select<ViewModelStudent3>() .Mapper(it => { it.Name = Md5(it.Name); //有多少列要處理寫多少列,能用Mapper的就少用Select兼容性更好些 }).ToList();
復制代碼

高性能的一對多查詢

我們也可以用Mapper來實現一對多,彌補.Select()不足

復制代碼
var s12 = db.Queryable<Student, School>((st, sc) => st.SchoolId == sc.Id).Select<ViewModelStudent3>() .Mapper((it, cache) => { var allSchools = cache.GetListByPrimaryKeys<School>(vmodel => vmodel.SchoolId); //in(ViewModelStudent3[0].SchoolId , ViewModelStudent3[1].SchoolId...) /*one to many*/ it.Schools = allSchools.Where(i => i.Id == it.SchoolId).ToList(); /*C# syntax conversion*/ it.Name = it.Name == null ? "null" : it.Name; }).ToList();
復制代碼

一對多查詢的性能可以秒殺其它ORM ,因為生成的SQL只有2條,並且這2條不會多查詢一條沒用的記錄,有幸趣的可以研究一下,其它的都內存處理

 

多Queryable查詢

Union all查詢將結果集合並

var getUnionAllList2 = db.UnionAll(db.Queryable<Student>(), db.Queryable<Student>()).ToList();//union all


 

兩個Queryable聯表查詢(有人說我只支持12表JOIN,那這樣就可以支持24張表了)

復制代碼
var q1 = db.Queryable<Student, School>((st,sc)=>new object[] { JoinType.Left,st.SchoolId==sc.Id }).Select((st, sc) => new ViewModelStudent4() { Id=st.Id, Name=st.Name,SchoolName=sc.Name }); var q2 = db.Queryable<School>(); var innerJoinList = db.Queryable(q1, q2, (j1, j2) => j1.Id == j2.Id).Select((j1, j2) => j1).ToList();//inner join var leftJoinList = db.Queryable(q1, q2,JoinType.Left, (j1, j2) => j1.Id == j2.Id).Select((j1, j2) => j1).ToList();/
復制代碼

 

二級緩存支持

二級緩存功能是對查詢出來的數據進行緩存,在緩存不失效的情況下,下次同樣的查詢操作都會從緩存內讀取

 

使用緩存查詢

var list=db.Queryable<Student, School>((s1, s2) => s1.Id == s2.Id).Select(s1 => s1).WithCache().ToList();//可以設置過期時間WithCache(60)

 

刪除緩存

我們需要刪除緩存也相當方便,只需要在對該表操作的時候加 RemoveDataCache 就能把查詢中引用該表的緩存全部清除

db.Deleteable<Student>().Where(it => it.Id == 1).RemoveDataCache().ExecuteCommand();

//Updateable和Insertable一樣用法

 

自動刪除緩存

SqlSugarClient db = new SqlSugarClient(new ConnectionConfig() { ConnectionString = Config.ConnectionString, MoreSettings =new ConnMoreSettings(){ IsAutoRemoveDataCache=true }

 

創建db對象

我們需要創建一個MyCache類,你可以用我寫好的也可以用你自已寫的實現緩存

 

復制代碼
ICacheService myCache = new RedisCache("10.1.249.196");//ICacheService SqlSugarClient db = new SqlSugarClient(new ConnectionConfig() { ConnectionString = Config.ConnectionString, DbType = DbType.SqlServer, IsAutoCloseConnection = true, ConfigureExternalServices = new ConfigureExternalServices() { DataInfoCacheService = new RedisCache() //RedisCache是繼承ICacheService自已實現的一個類 } }); 
復制代碼

我寫好的Cache類可以作為參考

Redis:

https://github.com/sunkaixuan/SqlSugar/blob/dev/Src/Asp.Net/SqlSugar.Extensions.DataCache/RedisCache.cs

.Net自帶Cache:

https://github.com/sunkaixuan/SqlSugar/blob/dev/Src/Asp.Net/SqlSugar.Extensions.DataCache/HttpRuntimeCache.cs

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM