接手了一個用EF來做的項目,由於項目中使用的原生處理,導致很多update都是采用先select 后 update的方式來實現,同時無法批量執行邏輯如:根據訂單類型統一更新狀態等。所以在經過了N多查找之后 發現了一個國外寫的擴展插件EntityFramework.Extended 。
Github:https://github.com/loresoft/EntityFramework.Extended
簡單說一下用法:
Deleting
//delete all users where FirstName matches
context.Users
.Where(u => u.FirstName == "firstname")
.Delete();
Update
//update all tasks with status of 1 to status of 2
context.Tasks
.Where(t => t.StatusId == 1)
.Update(t => new Task { StatusId = 2 });
//example of using an IQueryable as the filter for the update
var users = context.Users.Where(u => u.FirstName == "firstname");
context.Users.Update(users, u => new User {FirstName = "newfirstname"});
看示例代碼就已經很直觀了。
還有2個很少被人提到的功能:
將來的查詢
建立對你所需要的數據,並在第一時間在任何結果的查詢列表被訪問,所有數據都將在一個往返到數據庫服務器中檢索。降低數據查詢成本。使用此功能是附加一樣簡單.Future()您的查詢的末尾。要使用將來的查詢,確保導入EntityFramework.Extensions命名空間。
將來的查詢與下面的擴展方法創建...
- Future()
- FutureFirstOrDefault()
- FutureCount()
Demo
// build up queries
var q1 = db.Users
.Where(t => t.EmailAddress == "one@test.com")
.Future();
var q2 = db.Tasks
.Where(t => t.Summary == "Test")
.Future();
// this triggers the loading of all the future queries
var users = q1.ToList();
在上面的例子中,有2個查詢建立起來的,只要查詢中的一個被枚舉,它觸發兩個查詢的批次負載。
// base query
var q = db.Tasks.Where(t => t.Priority == 2);
// get total count
var q1 = q.FutureCount();
// get page
var q2 = q.Skip(pageIndex).Take(pageSize).Future();
// triggers execute as a batch
int total = q1.Value;
var tasks = q2.ToList();
在這個例子中,我們必須的任務列表共同senerio。為了使GUI設置尋呼控制,你需要一個總數。隨着未來我們可以批量在一起的查詢來獲得一個數據庫調用的所有數據。
將來的查詢通過創建保持IQuerable適當IFutureQuery對象工作。然后IFutureQuery對象存儲在IFutureContext.FutureQueries列表。然后,當IFutureQuery對象之一被枚舉,它調用回IFutureContext.ExecuteFutureQueries()經由LoadAction委托。ExecuteFutureQueries建立從所有的存儲IFutureQuery對象批量查詢。最后,所有的IFutureQuery對象與從查詢的結果進行更新。
查詢結果緩存
緩存查詢結果,請使用FromCache位於擴展方法EntityFramework.Extensions命名空間。下面是一個示例高速緩存查詢結果。簡單地構建LINQ查詢,你通常會,然后追加的FromCache擴展。
//query is cached using the default settings
var tasks = db.Tasks
.Where(t => t.CompleteDate == null)
.FromCache();
//query result is now cached 300 seconds
var tasks = db.Tasks
.Where(t => t.AssignedId == myUserId && t.CompleteDate == null)
.FromCache(CachePolicy.WithDurationExpiration(TimeSpan.FromSeconds(300)));
查詢結果Cache也支持標記緩存,以便您可以通過調用過期常見的緩存條目Expire上的高速緩存標記。
// cache assigned tasks
var tasks = db.Tasks
.Where(t => t.AssignedId == myUserId && t.CompleteDate == null)
.FromCache(tags: new[] { "Task", "Assigned-Task-" + myUserId });
// some update happened to Task, expire Task tag
CacheManager.Current.Expire("Task");
在CacheManager對供應商的支持。默認提供程序使用MemoryCache存儲緩存條目。要創建一個自定義的供應商,實施ICacheProvider。然后,自定義提供程序將需要在登記Locator容器。
// Replace cache provider with Memcached provider
Locator.Current.Register<ICacheProvider>(() => new MemcachedProvider());
審計日志
審計日志功能將捕捉到的變化隨時它們被提交到數據庫實體。審核日志僅捕獲那些上發生了變化,這些變化的實體,只有屬性的實體。該前和記錄值之后, AuditLogger.LastAudit就是在這個信息被舉行,是一個ToXml()可以很容易把審計日志轉換為XML,便於儲存方法。
審計日志可以通過在實體上或通過流利的配置API的屬性自定義。
流利的配置
// config audit when your application is starting up...
var auditConfiguration = AuditConfiguration.Default;
auditConfiguration.IncludeRelationships = true;
auditConfiguration.LoadRelationships = true;
auditConfiguration.DefaultAuditable = true;
// customize the audit for Task entity
auditConfiguration.IsAuditable<Task>()
.NotAudited(t => t.TaskExtended)
.FormatWith(t => t.Status, v => FormatStatus(v));
// set the display member when status is a foreign key
auditConfiguration.IsAuditable<Status>()
.DisplayMember(t => t.Name);
創建審核日志
var db = new TrackerContext();
var audit = db.BeginAudit();
// make some updates ...
db.SaveChanges();
var log = audit.LastLog;
問題歸納
- 為什么沒有 update方法 :缺少引用 using EntityFramework.Extensions;
- 錯誤:無法將類型system.data.* 轉化為 *.Iquery<entity>:Extended 版本與ef版本不對應,請在nuget中查詢匹配版本。
- Update 無效,請跟蹤sql 腳本 以區分生成的 update where條件是否正確,與lambda 的 常量.Equals(變量) 不同 他是按照順序生成sql where的所以 生成的 是 常量 is null or 。。。。。。請注意lambda 順序