다음을 통해 공유


방법: StructuralType 결과를 반환하는 쿼리 실행(EntityClient)

이 항목에서는 EntityCommand 개체를 사용하여 개념적 모델에 대해 명령을 실행하는 방법과 EntityDataReader를 사용하여 StructuralType 결과를 검색하는 방법을 보여 줍니다. EntityType, RowTypeComplexType 클래스는 StructuralType 클래스에서 파생됩니다.

이 예제의 코드를 실행하려면

  1. 프로젝트에 AdventureWorks Sales 모델을 추가하고 Entity Framework 를 사용하도록 프로젝트를 구성합니다. 자세한 내용은 방법: 엔터티 데이터 모델 마법사 사용(Entity Framework)을 참조하십시오.

  2. 응용 프로그램의 코드 페이지에서 다음 using 문(Visual Basic의 경우 Imports)을 추가합니다.

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

예제

이 예제에서는 EntityType 결과를 반환하는 쿼리를 실행합니다. 다음 쿼리를 ExecuteStructuralTypeQuery 함수에 인수로 전달하면 이 함수는 Products에 대한 정보를 표시합니다.

SELECT VALUE Product FROM AdventureWorksEntities.Products AS Product

다음과 같은 매개 변수가 있는 쿼리를 전달하는 경우 EntityParameter 개체를 EntityCommand 개체의 Parameters 속성에 추가합니다.

SELECT VALUE product FROM AdventureWorksEntities.Products 
    AS product where product.ListPrice >= @price
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
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());
            }
        }
    }
}

참고 항목

개념

Entity SQL 참조
Entity Framework용 EntityClient 공급자