Export (0) Print
Expand All

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 (Entity Framework).

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

    using System;
    using System.Collections.Generic;
    using System.Collections;
    using System.Data.Common;
    using System.Data;
    using System.IO;
    using System.Data.SqlClient;
    using System.Data.EntityClient;
    using 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 (EntityConnection conn = new EntityConnection("name=SchoolEntities"))
// Create a query that specifies to
// get a collection of only OnsiteCourses.

string esqlQuery = @"SELECT VAlUE onsiteCourse FROM
OFTYPE(SchoolEntities.Courses, SchoolModel.OnsiteCourse)
AS onsiteCourse";
using (EntityCommand cmd = new EntityCommand(esqlQuery, conn))
// Execute the command.
using (DbDataReader rdr = 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"]);

See Also

Build Date:

© 2014 Microsoft