简体   繁体   中英

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.

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?

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM