2013-09-23 62 views
2

我遇到了EF和謂詞構建器的問題。我已經完成了所有的指示,我很確定我做的都是正確的,但是當我運行SQL Profiler並檢查到數據庫的查詢時,它忽略了我的謂詞並獲取了表中的每條記錄,而這目前表格大約有600,000行,所以它稍微放慢了一些。我的謂詞然後在數據庫查詢後應用。實體框架和謂詞構建器 - 謂詞在SQL查詢中被忽略

有人可以告訴我我錯過了什麼嗎?

var predicate = PredicateBuilder.True<ListRecord>(); 

var classFilter = PredicateBuilder.False<ListRecord>(); 
classFilter = classFilter.Or(x => x.Community == "Air Force"); 
classFilter = classFilter.Or(x => x.Community == "Navy"); 
predicate = predicate.And(classFilter); 

// Add several more predicates just like classFlter 

var query = db.ListRecords.AsExpandable().Where(predicate.Compile()); 
var list = query.ToList(); 

,我已經複製的例子是http://www.albahari.com/nutshell/predicatebuilder.aspx

嵌套謂詞此處所說的正在生產的SQL:

SELECT 
[Extent1].[ListRecordId] AS [ListRecordId], 
[Extent1].[Community] AS [Community] 
-- And every other column from this table 
FROM [dbo].[ListRecord] AS [Extent1] 

回答

3

我不認爲你需要創建第一個謂語。不會返回你需要的結果嗎?

var classFilter = PredicateBuilder.False<ListRecord>(); 
classFilter = classFilter.Or(x => x.Community == "Air Force"); 
classFilter = classFilter.Or(x => x.Community == "Navy"); 

// Add several more predicates just like classFlter 

var query = db.ListRecords.AsExpandable().Where(classFilter); 
var list = query.ToList(); 

或者額外的謂詞像Classfilter:

var classFilter = PredicateBuilder.False<ListRecord>(); 
classFilter = classFilter.Or(x => x.Community == "Air Force"); 
classFilter = classFilter.Or(x => x.Community == "Navy"); 

var list = db.ListRecords.AsExpandable() 
    .Where(classFilter) 
    .Where(someOtherFilterLikeClassFilter) 
    .Where(AnotherOneLikeClassFilter) 
    .ToList(); 
+0

這就像,因爲我正在做一個嵌套查詢。查看http://www.albahari.com/nutshell/predicatebuilder.aspx上的嵌套謂詞示例 – Owen

+0

拆分謂詞並排除.compile(),就像第二個示例一樣,一次添加一個作業 – Owen