How to: Query Objects with Table-per-Hierarchy Inheritance (Entity Framework)

[This topic is pre-release documentation and is subject to change in future releases. Blank topics are included as placeholders.]

This topic shows how to execute a polymorphic query using the OfType operator.

To run the code in this example

  1. Add the School Model to your project and configure your project to use the Entity Framework. For more information, see How to: Use the Entity Data Model Wizard (Entity Framework).

  2. Modify the conceptual model to have a table-per-hierrachy inheritance by following the steps in Walkthrough: Mapping Inheritance - Table-per-Hierarchy (Entity Data Model Tools).

Example

The following example uses an OfType operator to get and display a collection of only Instructor objects from a collection of People.


try
{
    using (SchoolEntities context =
                          new SchoolEntities())
    {
        int courseId = 1045;
        // Get all people for the supplied CourseID
        Course instructorQuery = context.Courses.Where(
            "it.CourseID = @courseID", new ObjectParameter
                ("courseID", courseId)).Include("People").
                FirstOrDefault();


        // Display instructors for the specified course.
        foreach (Instructor instructor in instructorQuery.People.
            OfType<Instructor>())
        {
            Console.WriteLine("Instructor: " + instructor.
                LastName + ", " + instructor.FirstName);
        }
    }

}
catch (System.Data.MappingException e)
{
    Console.WriteLine(e.ToString());
}
catch (System.Data.EntityException e)
{
    Console.WriteLine(e.ToString());
}

See Also

Show: