方法: StructuralType 結果を返すクエリを実行する

このトピックでは、EntityCommand オブジェクトを使用して概念モデルに対してコマンドを実行する方法と、StructuralType を使用して EntityDataReader の結果を取得する方法を示します。 EntityTypeRowType および ComplexType クラスは、StructuralType クラスから派生します。

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

  1. AdventureWorks Sales Model をプロジェクトに追加し、Entity Framework が使用されるようにプロジェクトを構成します。 詳細については、Entity Data Model ウィザードを使用する」を参照してください。

  2. アプリケーションのコード ページで、次の using ステートメント (Visual Basic の場合は Imports) を追加します。

    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;
    
    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
    
    

この例は、EntityType の結果を返すクエリを実行します。 次のクエリを引数として ExecuteStructuralTypeQuery 関数に渡すと、この関数は、Products に関する詳細を表示します。

SELECT VALUE Product FROM AdventureWorksEntities.Products AS Product

パラメーター化されたクエリを渡す場合は、次のように、EntityParameter オブジェクトの Parameters プロパティに EntityCommand オブジェクトを追加します。

SELECT VALUE product FROM AdventureWorksEntities.Products
    AS product where product.ListPrice >= @price
static void ExecuteStructuralTypeQuery(string esqlQuery)
{
    if (esqlQuery.Length == 0)
    {
        Console.WriteLine("The query string is empty.");
        return;
    }

    using (EntityConnection conn =
        new EntityConnection("name=AdventureWorksEntities"))
    {
        conn.Open();

        // Create an EntityCommand.
        using (EntityCommand cmd = conn.CreateCommand())
        {
            cmd.CommandText = esqlQuery;
            // Execute the command.
            using (EntityDataReader rdr =
                cmd.ExecuteReader(CommandBehavior.SequentialAccess))
            {
                // Start reading results.
                while (rdr.Read())
                {
                    StructuralTypeVisitRecord(rdr as IExtendedDataRecord);
                }
            }
        }
        conn.Close();
    }
}

static void StructuralTypeVisitRecord(IExtendedDataRecord record)
{
    int fieldCount = record.DataRecordInfo.FieldMetadata.Count;
    for (int fieldIndex = 0; fieldIndex < fieldCount; fieldIndex++)
    {
        Console.Write(record.GetName(fieldIndex) + ": ");

        // If the field is flagged as DbNull, the shape of the value is undetermined.
        // An attempt to get such a value may trigger an exception.
        if (record.IsDBNull(fieldIndex) == false)
        {
            BuiltInTypeKind fieldTypeKind = record.DataRecordInfo.FieldMetadata[fieldIndex].
                FieldType.TypeUsage.EdmType.BuiltInTypeKind;
            // The EntityType, ComplexType and RowType are structural types
            // that have members.
            // Read only the PrimitiveType members of this structural type.
            if (fieldTypeKind == BuiltInTypeKind.PrimitiveType)
            {
                // Primitive types are surfaced as plain objects.
                Console.WriteLine(record.GetValue(fieldIndex).ToString());
            }
        }
    }
}
Private Shared Sub ExecuteStructuralTypeQuery(ByVal esqlQuery As String)
    If esqlQuery.Length = 0 Then
        Console.WriteLine("The query string is empty.")
        Exit Sub
    End If

    Using conn As New EntityConnection("name=AdventureWorksEntities")
        conn.Open()

        ' Create an EntityCommand. 
        Using cmd As EntityCommand = conn.CreateCommand()
            cmd.CommandText = esqlQuery
            ' Execute the command. 
            Using rdr As EntityDataReader = cmd.ExecuteReader(CommandBehavior.SequentialAccess)
                ' Start reading results. 
                While rdr.Read()
                    StructuralTypeVisitRecord(TryCast(rdr, IExtendedDataRecord))
                End While
            End Using
        End Using
        conn.Close()
    End Using
End Sub

Private Shared Sub StructuralTypeVisitRecord(ByVal record As IExtendedDataRecord)
    Dim fieldCount As Integer = record.DataRecordInfo.FieldMetadata.Count
    For fieldIndex As Integer = 0 To fieldCount - 1
        Console.Write(record.GetName(fieldIndex) & ": ")

        ' If the field is flagged as DbNull, the shape of the value is undetermined. 
        ' An attempt to get such a value may trigger an exception. 
        If record.IsDBNull(fieldIndex) = False Then
            Dim fieldTypeKind As BuiltInTypeKind = record.DataRecordInfo.FieldMetadata(fieldIndex).FieldType.TypeUsage.EdmType.BuiltInTypeKind
            ' The EntityType, ComplexType and RowType are structural types 
            ' that have members. 
            ' Read only the PrimitiveType members of this structural type. 
            If fieldTypeKind = BuiltInTypeKind.PrimitiveType Then
                ' Primitive types are surfaced as plain objects. 
                Console.WriteLine(record.GetValue(fieldIndex).ToString())
            End If
        End If
    Next
End Sub

関連項目