I’ve been reading that Ienumerables don’t run straight away. So I’m trying to find the best way to query a list.
Below is my getAll method. Followed by my filter method. Followed by a preferred filter method (Readability).
My question is, will the 3rd method be the same as querying directly? In other words, will it, or won’t it Load ALL myObjects from the DB and then filter? Or filter when getting from the DB.
public static IEnumerable<myObject> getAll()
{
using (var db = Database.OpenConnectionString(blahblah))
{
var queryResults = db.Query("SELECT * FROM vu_myObjects");
return queryResults .Select(x => new myObject(x.myObjectName, x.myObjectF));
}
}
public static IEnumerable<myObject> getAllForFilter(String filter)
{
using (var db = Database.OpenConnectionString(blahblah))
{
var queryResults = db.Query("SELECT * FROM vu_myObjects WHERE ObjectF = @0", filter);
return queryResults.Select(x => new myObject(x.myObjectName, x.ObjectF));
}
}
public static IEnumerable<myObject> getAllForFilter(String filter)
{ // Not checked syntax.
return getAll().Where(x => x.ObjectF = filter);
}
Alternatively, if you have a better suggestion, I’m all ears.
It won’t as you haven’t actually queried the database yet.
IQueryable<T>has deferred exection therefore in order to actually return a result set you need to execute the query. This can be done in a couple of ways e.g. callingToListor iterating the list.Any filtering i.e. your
Whereclause, would be done DB side.Actually, the code you have at the moment won’t even work – it would throw an
ObjectDisposedExceptionbecause you are trying to apply a filter on a delayed query after disposing the data context. For your code to work you would need to either pass in thewhereclause as a parameter to yourgetAllmethod e.g.Update
As you have just pointed out that you are using
WebMatrix.Databasenone of the above applies as there is no deferred execution happening here. The Query method executes immediately and returns a result set ofIEnumerable<T>so any filtering applied afterwords would be done in memory. So in terms of efficiency, the first filter method would be better as it does everything at the DB side.You may be able to get both readability & efficiency by converting the
Whereclause to the actual string and appending it to your query.