如何:执行返回 RefType 结果的查询

本主题演示如何使用 EntityCommand 对象针对概念模型执行命令,以及如何使用 RefType 检索 EntityDataReader 结果。

运行本示例中的代码

  1. AdventureWorks 销售模型添加到项目并将项目配置为使用实体框架。 有关详细信息,请参阅如何:使用实体数据模型向导

  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
    
    

示例

本示例执行返回 RefType 结果的查询。 如果你将以下查询作为自变量传递给 ExecuteRefTypeQuery 函数,该函数会返回一个对实体的引用:

SELECT REF(p) FROM AdventureWorksEntities.Products as p

如果传递参数化查询(如下面的查询),请将 EntityParameter 对象添加到 Parameters 对象的 EntityCommand 属性。

SELECT REF(p) FROM AdventureWorksEntities.Products as p WHERE p.ProductID == @productID
static public void ExecuteRefTypeQuery(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())
                {
                    RefTypeVisitRecord(rdr as IExtendedDataRecord);
                }
            }
        }
        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);
            }
        }
    }
}
Private Shared Sub ExecuteRefTypeQuery(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()
                    RefTypeVisitRecord(TryCast(rdr, IExtendedDataRecord))
                End While
            End Using
        End Using
        conn.Close()
    End Using
End Sub

Private Shared Sub RefTypeVisitRecord(ByVal record As IExtendedDataRecord)
    ' For RefType the record contains exactly one field. 
    Dim fieldIndex As Integer = 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 = TryCast(record.GetValue(fieldIndex), EntityKey)
            ' Get the EntitySet name. 
            Console.WriteLine("EntitySetName " & key.EntitySetName)
            ' Get the Name and the Value information of the EntityKey. 
            For Each keyMember As EntityKeyMember In key.EntityKeyValues
                Console.WriteLine(" Key Name: " & keyMember.Key)
                Console.WriteLine(" Key Value: " & keyMember.Value)
            Next
        End If
    End If
End Sub

请参阅