Reputation: 45961
I'm developing a library with C#, Entity Framework Code First 4.4.0.0 and .NET Framework 4.0.
I have this code:
string[] keywords = null;
if (query_string != null)
keywords = query_string.Split(' ');
// Check parameter. It will throw an exception.
ParameterCheck.CheckObjectId(user_id);
// Convert parameter to int.
int userId = Int32.Parse(user_id);
try
{
using (var context = new AdnLineContext())
{
context.Configuration.ProxyCreationEnabled = false;
//IQueryable<User> query = context.Users;
IQueryable<User> query = context.Users.AsExpandable();
var predicate = PredicateBuilder.False<User>();
foreach (string keyword in keywords)
{
string temp = keyword;
predicate = predicate.Or(u => u.Name.Contains(temp) ||
u.State.Contains(temp) ||
u.HashTags.Contains(temp));
}
query.Where(predicate);
query.Include("WhoHasBlockedMe").Include("Friends");
var users = query.ToList();
[ ... ]
}
}
if keywords = {"john", "happy"}
I want to get this SQL:
select * from users where
users.name like '%john%' or
users.state like '%john%' or
users.hashtags like '%john%' or
users.name like '%happy%' or
users.state like '%happy%' or
users.hashtags like '%happy%';
How can I do that with PredicateBuilder?
By the way, I have downloaded LinqKit from http://www.albahari.com/nutshell/predicatebuilder.aspx
UPDATE
I have added a breakpoint at var users = query.ToList();
and query
has this SQL:
{SELECT
[Extent1].[UserId] AS [UserId],
[...]
FROM [dbo].[Users] AS [Extent1]}
It doesn't have a Where
clause.
Upvotes: 1
Views: 1104
Reputation: 152624
Your problem is here:
query.Where(predicate);
query.Include("WhoHasBlockedMe").Include("Friends");
var users = query.ToList();
.Where
and .Include
don't modify the underlying query, they return a new query.
Use
query = query.Where(predicate);
query = query.Include("WhoHasBlockedMe").Include("Friends");
var users = query.ToList();
instead.
Upvotes: 5
Reputation: 203825
What's the result of true OR something Or SomethingElse
?
Do you even need to know what something
is?
It will always be true
.
You need to start out with False
, not True
. False Or anything
is equivalent to anything
.
If you were AND-ing items, you'd start with true, given that true AND anything
is equivalent to anything
.
Upvotes: 1