This documentation is archived and is not being maintained.

How to: Execute a Polymorphic Query

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

  2. In the code page for your application, add the following using statements (Imports in Visual Basic):

    Imports System
    Imports System.Collections.Generic
    Imports System.Collections
    Imports System.Data.Common
    Imports System.Data
    Imports System.IO
    Imports System.Data.SqlClient
    Imports System.Data.EntityClient
    Imports System.Data.Metadata.Edm
  3. Modify the conceptual model to have a table-per-hierrachy inheritance by following the steps in Walkthrough: Mapping Inheritance - Table per Hierarchy.


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

Using conn As New EntityConnection("name=SchoolEntities")
    ' Create a query that specifies to 
    ' get a collection of only OnsiteCourses. 

    Dim esqlQuery As String = "SELECT VAlUE onsiteCourse FROM " & _
        "OFTYPE(SchoolEntities.Courses, SchoolModel.OnsiteCourse) AS onsiteCourse"
    Using cmd As New EntityCommand(esqlQuery, conn)
        ' Execute the command. 
        Using rdr As DbDataReader = cmd.ExecuteReader(CommandBehavior.SequentialAccess)
            ' Start reading. 
            While rdr.Read()
                ' Display OnsiteCourse's location. 
                Console.WriteLine("CourseID: {0} ", rdr("CourseID"))
                Console.WriteLine("Location: {0} ", rdr("Location"))
            End While
        End Using
    End Using
End Using

See Also