using .Equals() failing in Predicatebuilder
-
29-04-2021 - |
Question
Hi I am using Predicate builder to build up my where clause. I noticed that it was doing a case sensitive comparison against the entity datasource. Some quick googling implies this is a feature of linqtoentities. so i have had to modify my code to do
whereClause = whereClause.And(x => x.county.Equals(oSearch.County, StringComparison.OrdinalIgnoreCase ));
rather than previously doing
whereClause = whereClause.And(x => x.county == oSearch.County);
The problem is now it appears to be failing building a whereclause.
incidentally i am using the code below which was working before.
var tbl = db.tbl_members.AsExpandable().Where(whereClause.Compile());
I have code which does a foreach (var item in Model) this is now failing with a "Object reference not set to an instance of an object" if i examine the model using quick view it now shows this
tblMembers = {System.Linq.Enumerable.WhereEnumerableIterator<tbl_members>}
rather than
tblMembers = {SELECT [Extent1].[id] AS [id],
[Extent1].[membership_id] AS [membership_id],
[Extent1].[membership_type] AS [membership_type],
[Extent1].[institution] AS [institution],
[Extent1].[full_name] AS [full_name],
[Extent1].[address1] AS [address1],
...
which it showed previously regardless of any results or not.
La solution
Given this:
tblMembers = {System.Linq.Enumerable.WhereEnumerableIterator<tbl_members>}
it looks like you're inadvertently using LINQ to Objects. Check whether your copy of PredicateBuilder is actually in terms of expression trees (Expression<Func<T, bool>>
) or delegates (Func<T, bool>
) - you should be using expression trees.
EDIT: As noted in comments, this is the problem:
var tbl = db.tbl_members.AsExpandable().Where(whereClause.Compile());
That's compiling the expression tree into a delegate, and then calling Enumerable.Where
. Without the Compile()
call:
var tbl = db.tbl_members.AsExpandable().Where(whereClause);
... we end up calling Queryable.Where
using the expression tree, which can then be converted into SQL.
Autres conseils
The problem is that linq has translation for
whereClause = whereClause.And(x =>
x.county.Equals(oSearch.County,StringComparison.OrdinalIgnoreCase )
in the sql. You can try:
whereClause = whereClause.And(x => x.county.ToLower()==oSearch.County.ToLower());