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 (SchoolEntities context =
                          new SchoolEntities())
    {
        int departmentID = 7;
        // Get courses for the department with id 7.
        IQueryable<Course> courses = context.Departments
                .Where(d => d.DepartmentID == departmentID)
                .SelectMany(d => d.Courses);

        Console.WriteLine("All the courses for the selected department.");
        foreach (Course course in courses)
        {
            Console.WriteLine("CourseID: {0} ", course.CourseID);

        }
        var onlineCourses = courses.OfType<OnlineCourse>();
        Console.WriteLine("Online courses only for the selected department.");
        foreach (OnlineCourse onlineCourse in onlineCourses)
        {
            Console.WriteLine("CourseID: {0} ", onlineCourse.CourseID);

        }
        var onsiteCourses = courses.OfType<OnsiteCourse>();
        Console.WriteLine("Onsite courses only for the selected department.");
        foreach (OnsiteCourse onsite in onsiteCourses)
        {
            Console.WriteLine("CourseID: {0} ", onsite.CourseID);

        }
    }

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


See Also

Community Additions

ADD
Show:
© 2014 Microsoft