Matt Johnson-Pint
Matt Johnson-Pint

Reputation: 241738

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.

See: http://msdn.microsoft.com/en-us/library/bb399295.aspx

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?

Upvotes: 1

Views: 1119

Answers (1)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364369

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();

Upvotes: 5

Related Questions