HOW TO:執行多型查詢 (EntityClient)

本主題將示範如何使用 OFTYPE 運算子來執行 Entity SQL 多型查詢。

若要執行這個範例中的程式碼

  1. 建置 CourseManager 應用程式。如需詳細資訊和指示,請參閱 Entity Framework 快速入門

  2. 藉由完成 Walkthrough: Mapping Inheritance - Table per Hierarchy中<實作每個階層的資料表繼承>一節的指示,修改其 EDM。

範例

OFTYPE 運算式會指定針對集合的每個元素執行型別測試所發出的型別運算式。OFTYPE 運算式會產生指定之型別的新集合,其中僅包含相當於該型別或其子型別的元素。例如,假設 ManagerEmployee 的子型別,下列運算式就會從員工集合中產生只有主管的集合:

OfType(employees, Manager)

下列範例會使用 OFTYPE 運算子,從 People 的集合中取得並顯示只有 Students 的集合。

Using connection As EntityConnection = New EntityConnection("name= SchoolEntities ")
    connection.Open()

    ' Create a query that specifies to 
    ' get a collection of Students
    ' with enrollment dates from
    ' a collection of People.
    Dim esqlQuery As String = "SELECT Student.LastName, " & _
            " Student.EnrollmentDate FROM " & _
            " OFTYPE(SchoolEntities.Person, " & _
            " SchoolModel.Student) AS Student "

    ' Create an EntityCommand and pass the connection object 
    ' and Enity SQL query to its constructor.
    Using command As EntityCommand = New EntityCommand(esqlQuery, connection)
        ' Execute the command.
        Using reader As DbDataReader = command.ExecuteReader(CommandBehavior.SequentialAccess)
            ' Start reading.
            Do While reader.Read
                ' Display student's last name and enrollment date.
                Console.Write(reader.Item("LastName"))
                Console.WriteLine(reader.Item("EnrollmentDate"))
            Loop
        End Using
    End Using
End Using
using (EntityConnection conn = new EntityConnection("name=SchoolEntities"))
{
    conn.Open();
    // 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 
        OFTYPE(SchoolEntities.Person, 
        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"] + " ");
                Console.WriteLine(rdr["EnrollmentDate"]);
            }
        }
    }
}

另請參閱

概念

Entity SQL 語言

其他資源

Working with EntityClient
How to: Execute an Entity SQL Query Using EntityCommand
How to: Create and Execute Object Queries using Table per Hierarchy Inheritance