实体框架和谓词生成器 - 谓词在SQL查询中被忽略

时间:2013-09-23 13:45:09

标签: sql entity-framework predicate predicatebuilder

我遇到了EF和Predicate Builder的问题。我已经完成了所有的说明,我很确定我正在做的一切正确,但是当我运行SQL事件探查器并检查查询到数据库时,它忽略了我的谓词并获取表中的每条记录,而这table目前大约有600,000行,所以它会减慢一些。然后在查询数据库后应用我的谓词。

有人可以告诉我我错过了什么吗?

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]

1 个答案:

答案 0 :(得分: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();