Freigeben über


Gewusst wie: Ausführen einer Abfrage, die StructuralType-Ergebnisse zurückgibt (EntityClient)

In diesem Thema finden Sie ein Beispiel, wie ein Befehl anhand eines Entity Data Model unter Verwendung von EntityCommand ausgeführt wird, und wie die StructuralType-Ergebnisse mithilfe von EntityDataReader abgerufen werden. EntityType, RowType und ComplexType werden vom StructuralType abgeleitet.

So führen Sie den Code in diesem Beispiel aus

  1. Fügen Sie dem Projekt das "AdventureWorks Sales"-Modell hinzu, und konfigurieren Sie das Projekt für die Verwendung des Entity Framework. Gehen Sie dazu folgendermaßen vor:

  2. Fügen Sie der Codepage Ihrer Anwendung die folgenden using-Anweisungen (Imports in Visual Basic) hinzu:

    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;
    

Beispiel

Um den Code zu testen, übergeben Sie die folgende Abfrage als Argument zur ExecuteStructuralTypeQuery-Funktion:

"SELECT VALUE Product FROM AdventureWorksEntities.Product AS Product"

Die obige Abfrage gibt die EntityType-Ergebnisse zurück.

Sub ExecuteStructuralTypeQuery(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())
                        StructuralTypeVisitRecord(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 StructuralTypeVisitRecord(ByVal record As IExtendedDataRecord)
    Dim fieldCount As Integer
    fieldCount = record.DataRecordInfo.FieldMetadata.Count
    Dim fieldIndex As Integer
    For fieldIndex = 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();

        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())
                    {
                        StructuralTypeVisitRecord(rdr as IExtendedDataRecord);
                    }
                }
            }
        }
        catch (EntityException ex)
        {
            Console.WriteLine(ex.ToString());
        }
        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());
            }
        }
    }
}

Siehe auch

Konzepte

Entity SQL-Referenz

Weitere Ressourcen

Arbeiten mit EntityClient (Entity Framework-Aufgaben)