I have a set of subclassed domain objects that I fetch with Linq and NHibernate. Here’s an example of what I have:
public abstract class Car {
public abstract bool Runs();
}
public class Junker : Car {
public override bool Runs() {
return false;
}
}
public class NewCar : Car {
public override bool Runs() {
return true;
}
}
What I need to do is to fetch only the cars that Run(). So, I want to do this:
var goodCars = _session.Query<Car>().Where(car => car.Runs());
… but, that doesn’t work because Runs() isn’t a supported query source. Here’s the error I get:
Cannot parse expression 'car' as it has an unsupported type. Only query sources (that is, expressions that implement IEnumerable) and query operators can be parsed.
I’ve tried separating the query into two steps: 1) get all cars, 2) filter by Runs() … but I can’t do this because it breaks Lazy Loading (my domain model is a bit more complex that my car example). Besides, I only want to fetch the items from the database that actually fit my query.
Is there a way to do what I’m trying to do?
You cannot do this. The thing you’re trying to do is impossible to translate into a SQL query and since that is all NHibernate is doing ultimately…no.
To get all with one query is going to require you dropping down to the db level and using some non-domain knowledge. I recommend hiding this behind a service interface.
public interface RunningCars {
IEnumerable All();
}
and implementing it using maybe a custom sql query or a stored procedure.
How does doing it in 2 steps break lazy loading? Perhaps you need to specify that you want to pre-fetch those asociations during the initial query.
Also in this specific example, couldn’t you just fetch all instances of NewCar?