Reputation: 45911
I'm developing an Entity Framework Code First 4.4.0.0 library with C# and .NET Framework 4.0.
I'm searching how can I create query dynamically, using arrays on where clause. And I have found this (here):
IQueryable<Product> SearchProducts (params string[] keywords)
{
IQueryable<Product> query = dataContext.Products;
foreach (string keyword in keywords)
{
string temp = keyword;
query = query.Where (p => p.Description.Contains (temp));
}
return query;
}
But I don't know how to use it. How can I run this query?
I usually do this:
using (var context = new MyContext())
{
context.Configuration.ProxyCreationEnabled = false;
var users = from u in context.Users.Include("WhoHasBlockedMe").Include("Friends")
from act in u.WantsToDo
where act.ActivityId == activityId &&
u.Gender == genderId &&
u.City == city &&
u.Country == countryIsoCode
select u;
// This user doesn't exit on database
if ((users == null) ||
(users.Count() == 0))
{
ctx.StatusCode = System.Net.HttpStatusCode.NotFound;
ctx.SuppressEntityBody = true;
}
else
{
usersList = new List<UserProfile>();
foreach(User us in users.ToList())
{
usersList.Add(UserProfile.CreateUserView(us, userId));
}
ctx.StatusCode = System.Net.HttpStatusCode.OK;
}
}
How can I run that query?
Upvotes: 0
Views: 13364
Reputation: 19567
You should execute your query and get results:
query.ToList()
In your example, it will be looks, like this:
var users = SearchProducts().ToList();
if ((users == null) || (users.Count() == 0))
{
ctx.StatusCode = System.Net.HttpStatusCode.NotFound;
ctx.SuppressEntityBody = true;
}
else
{
usersList = new List<UserProfile>();
foreach(User us in users)
{
usersList.Add(UserProfile.CreateUserView(us, userId));
}
ctx.StatusCode = System.Net.HttpStatusCode.OK;
}
Upvotes: 1