[英]Run an IQueryable with Entity Framework
I'm developing an Entity Framework Code First 4.4.0.0 library with C# and .NET Framework 4.0. 我正在使用C#和.NET Framework 4.0开发Entity Framework Code First 4.4.0.0库。
I'm searching how can I create query dynamically, using arrays on where clause. 我正在搜索如何使用where子句上的数组动态创建查询。 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? 如何运行该查询?
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.