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

☆樱花仙子☆ 提交于 2019-12-24 01:29:28

问题


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]

回答1:


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


来源:https://stackoverflow.com/questions/18960885/entity-framework-and-predicate-builder-predicates-being-ignored-in-sql-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!