Querying Entity Framework Code First Inheritance
This is a short post to complement my previous one on Entity Framework Code First Inheritance: how to query for a specific class. The options are:
-
From the DbContext collection:
1: IEnumerable<DerivedA> derived = ctx.Bases.OfType<DerivedA>().ToList();
- From the inner ObjectContext, using Entity SQL and the OFTYPE operator:
1: IEnumerable<DerivedA> derived = (ctx as IObjectContextAdapter).ObjectContext.CreateQuery<DerivedA>("SELECT VAlUE b FROM OFTYPE(Bases, MyNamespace.DerivedA) AS b").OfType<DerivedA>().ToList();
- Also in Entity SQL, using TREAT and IS OF:
1: IEnumerable<DerivedA> derived = (ctx as IObjectContextAdapter).ObjectContext.CreateQuery<DerivedA>("SELECT VAlUE TREAT(b AS MyNamespace.DerivedA) FROM Bases AS b WHERE b IS OF (ConsoleApplication1.DerivedA)").OfType<DerivedA>().ToList();
- Using LINQ to Entities:
1: IEnumerable<DerivedA> derived = (from d in ctx.Bases where d is DerivedA select d as DerivedA).ToList();
- Using pure SQL:
1: IEnumerable<DerivedA> derived = ctx.Database.SqlQuery<DerivedA>("SELECT * FROM Bases AS b WHERE b.Discriminator = 'DerivedA'").ToList();