Tip 5 - How to restrict the types returned from an EF Query.

Imagine you have a model that looks like this:

CarHierarchy

 

How do you query for just Cars?

This is where OfType<SubType>() comes in. You write something like this:

var onlyCars = from car in ctx.Vehicles.OfType<Car>()
               select car;

And this works, fine. It restricts the results to just Cars, which incidentally includes Cars, SportsCars and SUVs.

How do you query for just Cars without Sub-Types?

Imagine however your budget only stretches to a simple family car. This means you don't want SUVs and SportsCars.

Now to avoid pulling back all sub-types you need to be very explicit in your query:

var onlyCars = from car in ctx.Vehicles.OfType<Car>()
               where !(car is SportsCar) && !(car is SUV)
               select car;

And now you have something that brings back just the Cars.

Extra Credit

The only unfortunate thing about this solution is that you have to explicitly call out all the possible subtypes you don't want, which in the case of a deep or wide hierarchy might be a lot of types.

It would be better if this was supported (which unfortunately it isn't):

var onlyCars = from car in ctx.Vehicles.OfType<Car>()
               where car.GetType() == typeof(Car)
               select car;

The question is how important do you think it is for us to support this kind of query?