Entity Framework and Predicate Builder - Predicates being Ignored in SQL Query

Owen picture Owen · Sep 23, 2013 · Viewed 7k times · Source

I'm having a problem with EF and Predicate Builder. I've been through all the instructions and I'm pretty sure I'm doing everything right, but when I run SQL Profiler and inspect the query going to the database, it's ignoring my predicates and getting every record in the table, and this table is currently up to about 600,000 rows so it slows things down a little. My predicates then get applied after the database has queried.

Can someone please tell me what I'm missing?

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();

The example that I've copied is Nesting Predicates on http://www.albahari.com/nutshell/predicatebuilder.aspx

This is the SQL that's being produced:

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

Answer

Adam picture Adam · Sep 23, 2013

I don't think you need the first predicate you create. Wont this return the results you need?

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();

Or with additional predicates like 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();