Export (0) Print
Expand All

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 (Entity Framework).

  2. 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;
        
    
  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 (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();
}
    




Build Date:

2012-08-02
Show:
© 2014 Microsoft