How to do OFTYPE ONLY in EF Code First with Linq?
When using traditional Entity Framework and querying with ESQL, you can use OFTYPE with ONLY to only return base types.
In Entity Framework Code First, I have inheritance set up where B is a subtype of A. Performing MyContext.Set<A>().OfType<A>() still returns elements of type B. Ideally, I would like to call MyContext.Set<A>().OfOnlyType<A>() and it would translate the same way as when using ESQL's OFTYPE ONLY.
I also found I can use the is operator in a where statement, but again, that will return both A and B entities.
How can I write a linq expression that will filter to only elements of type A?
There is no way to get only A instances directly (equivalent to ONLY) in Linq-to-entities unless you somehow exclude derived instances from the result set. For example:
var list = MyContext.Set<A>().Where(a => !(a is B)).ToList();