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

이 항목에서는 EntityCommand를 사용하여 엔터티 데이터 모델에 대해 명령을 실행하는 방법 및 EntityDataReader를 사용하여 RefType 결과를 검색하는 방법의 예제를 제공합니다.

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

  1. 프로젝트에 AdventureWorks Sales 모델을 추가하고 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.Data.SqlClient
    Imports System.Data.EntityClient
    Imports System.Data.Metadata.Edm
    Imports System.IO
    ' Add AdventureWorksModel prepended with the root namespace for the project.
    'Imports ProjectName.AdventureWorksModel
    
    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 AdventureWorksModel;
    using System.Data.Metadata.Edm;
    

예제

코드를 테스트하려면 다음 쿼리를 ExectueRefTypeQuery 함수에 인수로 전달합니다.

"SELECT REF(p) FROM AdventureWorksEntities.Product as p"

위의 쿼리는 RefType 결과를 반환합니다.

Sub ExectueRefTypeQuery(ByVal esqlQuery As String)
    If (esqlQuery.Length = 0) Then
        Console.WriteLine("The query string is empty.")
        Return
    End If

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

        Try
            ' Create an EntityCommand.
            Using cmd As EntityCommand = conn.CreateCommand()
                cmd.CommandText = esqlQuery
                ' Execute the command.
                Using reader As EntityDataReader = cmd.ExecuteReader(CommandBehavior.SequentialAccess)
                    Do While (reader.Read())
                        RefTypeVisitRecord(CType(reader, IExtendedDataRecord))
                    Loop
                End Using
            End Using
        Catch ex As Exception
            Console.WriteLine(ex.ToString())
        End Try
        conn.Close()
    End Using
End Sub

Sub RefTypeVisitRecord(ByVal record As IExtendedDataRecord)
    ' For RefType the record contains exactly one field.
    Dim fieldIndex As Integer
    fieldIndex = 0

    ' 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()

        'read only fields that contain PrimitiveType
        If (fieldTypeKind = BuiltInTypeKind.RefType) Then
            ' Ref types are surfaced as EntityKey instances. 
            ' The containing record sees them as atomic.
            Dim key As EntityKey = CType(record.GetValue(fieldIndex), EntityKey)
            ' Get the EntitySet name.
            Console.WriteLine("EntitySetName " + key.EntitySetName)
            ' Get the Name and the Value information of the EntityKey.
            Dim keyMember As EntityKeyMember
            For Each keyMember In key.EntityKeyValues
                Console.WriteLine("   Key Name: " + keyMember.Key)
                Console.WriteLine("   Key Value: " + keyMember.Value)
            Next
        End If
    End If
End Sub
static void ExectueRefTypeQuery(string esqlQuery)
{
    if (esqlQuery.Length == 0)
    {
        Console.WriteLine("The query string is empty.");
        return;
    }

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

        try
        {
            // 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())
                    {
                        RefTypeVisitRecord(rdr as IExtendedDataRecord);
                    }
                }
            }
        }
        catch (EntityException ex)
        {
            Console.WriteLine(ex.ToString());
        }
        conn.Close();
    }
}

static void RefTypeVisitRecord(IExtendedDataRecord record)
{
    // For RefType the record contains exactly one field.
    int fieldIndex = 0;

    // 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;
        //read only fields that contain PrimitiveType
        if (fieldTypeKind == BuiltInTypeKind.RefType)
        {
            // Ref types are surfaced as EntityKey instances. 
            // The containing record sees them as atomic.
            EntityKey key = record.GetValue(fieldIndex) as EntityKey;
            // Get the EntitySet name.
            Console.WriteLine("EntitySetName " + key.EntitySetName);
            // Get the Name and the Value information of the EntityKey.
            foreach (EntityKeyMember keyMember in key.EntityKeyValues)
            {
                Console.WriteLine("   Key Name: " + keyMember.Key);
                Console.WriteLine("   Key Value: " + keyMember.Value);
            }
        }
    }
}

참고 항목

개념

Entity SQL 참조

기타 리소스

EntityClient 사용(Entity Framework 작업)