This documentation is archived and is not being maintained.

How to: Query Objects with Table-per-Type Inheritance

This topic shows how to execute a polymorphic query by 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.

  2. Modify the conceptual model to have table-per-type inheritance by following the steps in Walkthrough: Mapping Inheritance - Table per Type.


The following example uses the OfType method to get and display a collection of OnsiteCourses and a collection of OnlineCourses from a collection of Courses. OnsiteCourses and OnlineCourses are specific types of Courses.

    Using context As New SchoolEntities()
        Dim departmentID = 7
        ' Get courses for the department with id 7. 
        Dim courses As IQueryable(Of Course) = _
            context.Departments.Where(Function(d) d.DepartmentID = departmentID).SelectMany(Function(d) d.Courses)

        Console.WriteLine("All the courses for the selected department.")
        For Each course As Course In courses

            Console.WriteLine("CourseID: {0} ", course.CourseID)
        Dim onlineCourses = courses.OfType(Of OnlineCourse)()
        Console.WriteLine("Online courses only for the selected department.")
        For Each onlineCourse As OnlineCourse In onlineCourses

            Console.WriteLine("CourseID: {0} ", onlineCourse.CourseID)
        Dim onsiteCourses = courses.OfType(Of OnsiteCourse)()
        Console.WriteLine("Onsite courses only for the selected department.")
        For Each onsite As OnsiteCourse In onsiteCourses

            Console.WriteLine("CourseID: {0} ", onsite.CourseID)

    End Using
Catch e As System.Data.MappingException
Catch e As System.Data.EntityException
End Try

See Also