2

I have such class structure

public class Aclass { ... }
public class Bclass : Aclass { ... }
public class Cclass : Bclass { ... }

I try to get all data (by EF6) passing some condition and be only of type Bclass.

_dbContext.Aclasses
    .Where(condition)
    .Where(p => p is B)
    .ToList();

But my query download also object which are Cclass objects(I understand it's ok). I can add condition for

.Where(p is Bclass && !(p is Cclass))

but if I decide in future to add next derivation class I'll need to change such code.

My question is: how can I determine in EF query to get only specified objects, without derived objects?

Jacek
  • 11,661
  • 23
  • 69
  • 123
  • 2
    Have you read https://stackoverflow.com/questions/15853159/isassignablefrom-isinstanceoftype-and-the-is-keyword-what-is-the-difference? In your case simply compare the types: `p.GetType() == typeof(B)`. – MakePeaceGreatAgain Nov 29 '17 at 08:31
  • If you want the filtering done in the database, EF TPH makes use of a [Discriminator](https://stackoverflow.com/questions/7393788/entity-framework-code-first-creates-discriminator-column) which you can surely use as in the where predicate? – StuartLC Nov 29 '17 at 08:32
  • @StuartLC discriminator is not accessible on your model. Maybe creating a SQL view and map it to your entity. – CodeNotFound Nov 29 '17 at 08:56
  • Unfortunately the only supported operator in L2E queries is `is`, so what you are asking is not possible. – Ivan Stoev Nov 29 '17 at 09:12
  • [This answer here](https://stackoverflow.com/a/15772948/314291) analyses the generated Sql - seemingly the using `is` maps down to a Sql where on an `IN` clause of all Subtypes, as per Ivan's comment. – StuartLC Nov 29 '17 at 09:17
  • 1
    @HimBromBeere: typeof(T) is not supported by EF, – Jacek Nov 29 '17 at 16:43
  • @StuartLC how can I use discriminator in LINQ where statement? – Jacek Nov 29 '17 at 16:44
  • 2
    @Jacek That's the problem - you can't (EF hides it and does not allow you accessing it in the queries. Unnecessary over-encapsulation as most of the EF6 things). – Ivan Stoev Nov 29 '17 at 19:53

0 Answers0