Export (0) Print
Expand All
Expand Minimize

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.

Example

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.

Try
    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)
        Next
        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)
        Next
        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)
        Next

    End Using
Catch e As System.Data.MappingException
    Console.WriteLine(e.ToString())
Catch e As System.Data.EntityException
    Console.WriteLine(e.ToString())
End Try

See Also

Community Additions

ADD
Show:
© 2014 Microsoft