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:

  1. From the DbContext collection:
       1: IEnumerable<DerivedA> derived = ctx.Bases.OfType<DerivedA>().ToList();
  2. 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();
  3. 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();
  4. Using LINQ to Entities:
       1: IEnumerable<DerivedA> derived = (from d in ctx.Bases where d is DerivedA select d as DerivedA).ToList();
  5. Using pure SQL:
       1: IEnumerable<DerivedA> derived = ctx.Database.SqlQuery<DerivedA>("SELECT * FROM Bases AS b WHERE b.Discriminator = 'DerivedA'").ToList();

                             

No Comments

Add a Comment

As it will appear on the website

Not displayed

Your website