How to: Execute a Query that Returns Complex Types

This topic shows how to execute an Entity SQL query that returns entity type objects that contain a property of a complex type. 

To run the code in this example

  1. Add the AdventureWorks Sales Model to your project and configure your project to use the Entity Framework. For more information, see How to: Use the Entity Data Model Wizard.

  2. In the code page for your application, add the following using statements (Imports in Visual Basic):

    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;
    
  3. Double click the .edmx file to display the model in the Model Browser window of the Entity Designer. On the Entity Designer surface, select the Email and Phone properties of the Contact entity type, then right-click and select Refactor into New Complex Type.

  4. A new complex type with the selected Email and Phone properties is added to the Model Browser. The complex type is given a default name: rename the type to EmailPhone in the Properties window. Also, a new ComplexProperty property is added to the Contact entity type. Rename the property to EmailPhoneComplexType.

    For information about creating and modifying complex types by using the Entity Data Model Wizard, see How to: Refactor Existing Properties into a Complex Type Property (Entity Data Model Tools) and How to: Create and Modify Complex Types.

Example

The following example executes a query that returns a collection of Contact objects and displays two properties of the Contact objects: ContactID and the values of the EmailPhoneComplexType complex type.

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

    Dim esqlQuery As String = "SELECT VALUE contacts FROM" & _
        " AdventureWorksEntities.Contacts AS contacts WHERE contacts.ContactID == @id"

    ' Create an EntityCommand. 
    Using cmd As EntityCommand = conn.CreateCommand()
        cmd.CommandText = esqlQuery
        Dim param As New EntityParameter()
        param.ParameterName = "id"
        param.Value = 3
        cmd.Parameters.Add(param)
        ' Execute the command. 
        Using rdr As EntityDataReader = cmd.ExecuteReader(CommandBehavior.SequentialAccess)
            ' The result returned by this query contains 
            ' Address complex Types. 
            While rdr.Read()
                ' Display CustomerID 
                Console.WriteLine("Contact ID: {0}", rdr("ContactID"))
                ' Display Address information. 
                Dim nestedRecord As DbDataRecord = TryCast(rdr("EmailPhoneComplexProperty"), DbDataRecord)
                Console.WriteLine("Email and Phone Info:")
                For i As Integer = 0 To nestedRecord.FieldCount - 1
                    Console.WriteLine((" " & nestedRecord.GetName(i) & ": ") + nestedRecord.GetValue(i))
                Next
            End While
        End Using
    End Using
    conn.Close()
End Using
using (EntityConnection conn =
    new EntityConnection("name=AdventureWorksEntities"))
{
    conn.Open();

    string esqlQuery = @"SELECT VALUE contacts FROM
            AdventureWorksEntities.Contacts AS contacts 
            WHERE contacts.ContactID == @id";

    // Create an EntityCommand.
    using (EntityCommand cmd = conn.CreateCommand())
    {
        cmd.CommandText = esqlQuery;
        EntityParameter param = new EntityParameter();
        param.ParameterName = "id";
        param.Value = 3;
        cmd.Parameters.Add(param);

        // Execute the command.
        using (EntityDataReader rdr =
            cmd.ExecuteReader(CommandBehavior.SequentialAccess))
        {
            // The result returned by this query contains 
            // Address complex Types.
            while (rdr.Read())
            {
                // Display CustomerID
                Console.WriteLine("Contact ID: {0}",
                    rdr["ContactID"]);
                // Display Address information.
                DbDataRecord nestedRecord =
                    rdr["EmailPhoneComplexProperty"] as DbDataRecord;
                Console.WriteLine("Email and Phone Info:");
                for (int i = 0; i < nestedRecord.FieldCount; i++)
                {
                    Console.WriteLine("  " + nestedRecord.GetName(i) +
                        ": " + nestedRecord.GetValue(i));
                }
            }
        }
    }
    conn.Close();
}