Procedura: eseguire una query che restituisce risultati StructuralTypeHow to: Execute a Query that Returns StructuralType Results

In questo argomento viene illustrato come eseguire un comando su un modello concettuale usando un oggetto EntityCommand e viene mostrato come recuperare i risultati di StructuralType usando un oggetto EntityDataReader.This topic shows how to execute a command against a conceptual model by using an EntityCommand object, and how to retrieve the StructuralType results by using an EntityDataReader. Le classi EntityType, RowType e ComplexType derivano dalla classe StructuralType.The EntityType, RowType and ComplexType classes derive from the StructuralType class.

Per eseguire il codice in questo esempioTo run the code in this example

  1. Aggiungere il modello Sales di AdventureWorks al progetto e configurare il progetto utilizzerĂ  il Entity FrameworkEntity Framework.Add the AdventureWorks Sales Model to your project and configure your project to use the Entity FrameworkEntity Framework. Per ulteriori informazioni, vedere procedura: utilizzare la procedura guidata Entity Data Model.For more information, see How to: Use the Entity Data Model Wizard.

  2. Nella tabella codici per l'applicazione aggiungere le istruzioni using seguenti (Imports in Visual Basic):In the code page for your application, add the following using statements (Imports in Visual Basic):

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

EsempioExample

In questo esempio viene eseguita una query che restituisce risultati dell'oggetto EntityType.This example executes a query that returns EntityType results. Se si passa la query riportata di seguito come argomento alla funzione ExecuteStructuralTypeQuery, quest'ultima visualizza i dettagli relativi a Products:If you pass the following query as an argument to the ExecuteStructuralTypeQuery function, the function displays details about the Products:

SELECT VALUE Product FROM AdventureWorksEntities.Products AS Product

Se si passa una query con parametri, come quella riportata di seguito, aggiungere gli oggetti EntityParameter alla proprietĂ  Parameters nell'oggetto EntityCommand.If you pass a parameterized query, like the following, add the EntityParameter objects to the Parameters property on the EntityCommand object.

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

Vedere ancheSee Also

Riferimento a Entity SQLEntity SQL Reference
Provider EntityClient per Entity FrameworkEntityClient Provider for the Entity Framework