次の方法で共有


ポリモーフィック クエリを実行する方法 (EntityClient)

このトピックでは、OFTYPE 演算子を使ってポリモーフィックな Entity SQL クエリを実行する方法について説明します。

この例のコードを実行するには

  1. CourseManager アプリケーションを構築します。詳細情報と手順については、「Entity Framework クイック スタート」を参照してください。

  2. チュートリアル : Table-Per-Hierarchy 継承のマッピング」の「Table-Per-Hierarchy 継承の実装」セクションの手順を実行して、アプリケーションの EDM を変更します。

OFTYPE 式は、コレクションの各要素の型を判定するための式です。OFTYPE 式では、指定された型の新しいコレクションが生成されます。生成されたコレクションには、指定された型と同じか、そのサブタイプの要素だけが格納されます。たとえば、ManagerEmployee のサブタイプである場合、次の式からは、従業員 (employee) のコレクションのうち、マネージャ (manager) のコレクションだけが返されます。

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"]);
            }
        }
    }
}

参照

処理手順

Table-Per-Hierarchy 継承を使用してオブジェクト クエリを作成および実行する方法 (Entity Framework)

概念

Entity SQL 言語

その他のリソース

EntityClient の使用 (Entity Framework タスク)
How to: Execute an Entity SQL Query Using EntityCommand