采用EntityFramework.Extended 對EF進行擴展(Entity Framework 延伸系列2)


前言

Entity Framework 延伸系列目錄

今天我們來講講EntityFramework.Extended

首先科普一下這個EntityFramework.Extended是什么,如下:

這是一個對Entity Framework進行擴展的類庫.

完全支持EF 5.0/6.0+,

GitHub地址 https://github.com/loresoft/EntityFramework.Extended

最后一次更新是在2015/07/10

這個庫支持批量更新,刪除。查詢結果緩存和審計日志。

這個擴展對於每次批量操縱只生成一條sql語句,而不會像EntityFramework供給的原生辦法那樣批量N條數據就要生成N條sql語句

 

本文采用的環境與技術

系統:WIN7

數據庫:SQL Server2008

相關技術:MVC5+EF6.1.3+EntityFramework.Extended6.0

 

第一章:批量操作數據庫

批量刪除:

//記得引用
using EntityFramework.Extensions;
//這兩種寫法都可以,Context是你的EF上下文對象.
context.LogData.Delete(a => a.EntityKey == "aa");
context.LogData.Where(a => a.EntityKey == "aa").Delete();

 

批量更新:

//data為修改的行數
int   data =context.LogData.Where(a=>a.EntityKey=="aa").Update(b=> new LogData { EntityName = "ss" });
//第二種寫法,這種是針對DbSet的,已經標注過時了
 var data = context.LogData.Update(a => a.EntityKey == "aa",b=> new LogData { EntityName = "ss" });

批量增加:

//這個和Extended無關..EF本身就自帶了,單純的給新手一個實例而已,大神無視..
int data= context.LogData.AddRange(new List<LogData>());

 

第二章:批量查詢數據庫

批量查詢:

                    var count =context.LogData.FutureCount();
                    var data = context.LogData.FutureFirstOrDefault(); 
                    var datalist = context.LogData.Future();
                    //在同一個代碼上下文中,count,data,datalist這三個對象
                    //任意一個,第一次tolist或者.Value的時候,會連接一次數據庫
                    //同時查詢這三個數據,而不會分三次查詢
                    var datalists = datalist.ToList();
                    int countdata = count.Value;        

原理是這樣的:

E文原文:

Future queries work by creating the appropriate IFutureQuery object that keeps the IQuerable. The IFutureQuery object is then stored in IFutureContext.FutureQueries list. Then, when one of the IFutureQuery objects is enumerated, it calls back to IFutureContext.ExecuteFutureQueries() via the LoadAction delegate. ExecuteFutureQueries builds a batch query from all the stored IFutureQuery objects. Finally, all the IFutureQuery objects are updated with the results from the query.

本屌的辣雞二流子翻譯:

Future 會根據IQuerable創建出他自定義的IFutureQuery對象,然后將他加入到IFutureContext.FutureQueries查詢隊列當中,當隊列中的一個對象調用LoadAction那么就會執行IFutureContext.ExecuteFutureQueries()方法, ExecuteFutureQueries 會構建一個批處理查詢的IFutureQuery,最后將所有IFutureQuery的查詢結果進行更新(也就是查詢).

 

第三章:EF的數據審計日志

數據審計日志:

先說一下這個審計的概念,就是對所有的實體的操作(增,刪,改)進行監控.

我們先來看一下效果.

這是他追蹤到的信息,我們可以很方便的把這些信息存入數據庫或者你的日志存儲里(文本,XML,緩存)都行 隨你.

下面我們開始講解用法:

首先我們可以在應用程序的入口( Application_Start)配置(我這里以MVC的Web應用來舉例):

這里的配置可不加,用默認的也行,當然有需要的可以參考

https://github.com/loresoft/EntityFramework.Extended/wiki/Audit-Log

這里有更詳細的配置介紹

  protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            //這里是審計日志的配置
            var auditConfiguration = AuditConfiguration.Default;
            auditConfiguration.IncludeRelationships = true;
            auditConfiguration.LoadRelationships = false;
            auditConfiguration.DefaultAuditable = true;
           
        }

下面我們開始直接用,

舉個栗子:

                using (StudentInfoEntities us = new StudentInfoEntities())
                {
                    //開啟日志
                    var logaudit = us.BeginAudit();
                   //進行增刪改操作
                    us.LogData.Add(new LogData() { EntityKey = "aa", EntityName = "asd", Name = "asd" });
                    var data = us.LogData.Where(a => a.Id == 15).FirstOrDefault();
                    data.Name = "Test";
                    var delete = us.LogData.Where(a => a.Id == 9).FirstOrDefault();
                    us.LogData.Remove(delete);
                    //正常保存
                    us.SaveChanges();
                   //獲取審計日志
                    var log = logaudit.LastLog;
                    //將日志轉為XML字符串,或存入XML文件
                    string dda = log.ToXml();
                }

最終結果如下:

可以看到我們很方便的監控到了我們剛剛進行的三次操作.

(重要提示:這里需要注意的是,這里的審計日志只能監控到常規的寫法的增刪改,對於上面的批量增刪改很詭異的是監控不到的,作為自己寫的擴展庫,自己卻監控不到 - -,這不得不說是很蛋疼..)

 

 

第四章:查詢緩存

代碼如下:

//使用默認的緩存時間
var tasks = db.Tasks
    .Where(t => t.CompleteDate == null)
    .FromCache();

//查詢結果緩存300秒
var tasks = db.Tasks
    .Where(t => t.AssignedId == myUserId && t.CompleteDate == null)
    .FromCache(CachePolicy.WithDurationExpiration(TimeSpan.FromSeconds(300)));

這個我用的不多,就不詳細的贅述了,有興趣的朋友可以自行查看

https://github.com/loresoft/EntityFramework.Extended/wiki/Query-Result-Cache

 

寫在最后

文章到此就結束了,寫文章的過程也是自己溫故而知新的過程.寫的不好希望大神多多指正,我很希望能起到拋磚引玉的效果,上篇文章就得到了很多好的建議,希望大家不嗇賜教.


免責聲明!

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



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