Jason Guo
Jason Guo

Reputation: 33

Entity framework 4.1 : select by multiple conditions?

I have an Orders class with OrderID,OrderName,CreateTime, EndTime and so on ... Now,here is a method:

private TmpContext context = new TmpContext();
public List<Order> GetOrders(string id,string name,DateTime createTime)
{
      var list= context.Orders.AsEnumerable();
      if(!string.isNullOrEmpty(id))
           list = list.Where(l=>l.OrderID.Contains(id));
      if(!string.isNullOrEmpty(name))
           list = list.Where(l=>l.OrderName.Contains(name));
      // other conditions 

      return list.ToList();
}

I use the Linqpad,GetOrders(2124,"Cloth",DateTime.Now);find the sql is "select --- from Orders". It means all the Orders was Select.

What can i do with this situation. :D

Upvotes: 2

Views: 340

Answers (1)

Botz3000
Botz3000

Reputation: 39610

Remove the .AsEnumerable() call.

AsEnumerable casts your ObjectQuery to an IEnumerable<Order>, which prevents the compiler from finding the correct overloads (it will use Enumerable.Where instead of Queryable.Where, because list is of type IEnumerable<Order>). That's why only the first part of the query will be sent to the server ("select * from Orders"), the rest will be executed in memory.

If you remove the call to AsEnumerable, your conditions will be correctly applied to your ObjectQuery, allowing them to be executed on the server.

Upvotes: 4

Related Questions