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. 😀
Remove the
.AsEnumerable()call.AsEnumerablecasts your ObjectQuery to anIEnumerable<Order>, which prevents the compiler from finding the correct overloads (it will useEnumerable.Whereinstead ofQueryable.Where, becauselistis of typeIEnumerable<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.