MSDN Library

How to: Execute a Polymorphic Query (EntityClient)

This topic shows how to execute a polymorphic Entity SQL query using the OFTYPE operator.

To run the code in this example

  1. Build the CourseManager application. For more information and instructions, see the Entity Framework Quickstart.

  2. Modify its EDM by completing the instructions in the Implementing Table-per-Hierarchy Inheritance section in the Walkthrough: Mapping Inheritance - Table-per-Hierarchy.


An OFTYPE expression specifies a type expression that is issued to perform a type test against each element of a collection. The OFTYPE expression produces a new collection of the specified type that contains only those elements that were equivalent either to that type or to a sub-type of it. For example, given that a Manager is a subtype of Employee, the following expression produces a collection of only managers from a collection of employees:

OfType(employees, Manager)

The following example uses an OFTYPE operator to get and display a collection of only Students from a collection of People.

using (EntityConnection conn = new EntityConnection("name=SchoolEntities"))
    // Create a query that specifies to 
    // get a collection of only Students
    // with enrollment dates from 
    // a collection of People.
    string esqlQuery = @"SELECT Student.LastName, 
        Student.EnrollmentDate FROM 
        SchoolModel.Student) AS Student";

    using (EntityCommand cmd = new EntityCommand(esqlQuery, conn))
        // Execute the command.
        using (DbDataReader rdr = cmd.ExecuteReader(CommandBehavior.SequentialAccess))
            // Start reading.
            while (rdr.Read())
                // Display student's last name and enrollment date.
                Console.Write(rdr["LastName"] + " ");

See Also

Community Additions

© 2016 Microsoft