How to: Query Complex Types
This topic shows how to execute a query that returns entity type objects that contain a complex type property. For more information about complex types, see Complex Type Objects and How to: Create and Modify Complex Types.
To run the code in this example
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.
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;
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. A new complex type with the selected Email and Phone properties is added to the Model Browser.
Rename the new type to EmailPhone. Rename the property in the Contact entity type 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) andHow to: Create and Modify Complex Types.
Example
The following example executes a query that returns a collection of Contacts
. The Contact
type contains a complex type property, EmailPhoneComplexProperty
, that consists of an EmailAddress
property and a Phone
property. The example outputs the ContactID
property and the values of the EmailPhoneComplexType
complex type.
Using context As New AdventureWorksEntities()
Dim contacts = From contact In context.Contacts _
Where contact.ContactID = 3 _
Select contact
For Each contact As Contact In contacts
Console.WriteLine("Contact Id: " & contact.ContactID)
Console.WriteLine("Contact's email: " & contact.EmailPhoneComplexProperty.EmailAddress)
Console.WriteLine("Contact's phone#: " & contact.EmailPhoneComplexProperty.Phone)
Next
End Using
using (AdventureWorksEntities context =
new AdventureWorksEntities())
{
var contacts =
from contact in context.Contacts
where contact.ContactID == 3
select contact;
foreach (Contact contact in contacts)
{
Console.WriteLine("Contact Id: " + contact.ContactID);
Console.WriteLine("Contact's email: " + contact.EmailPhoneComplexProperty.EmailAddress);
Console.WriteLine("Contact's phone#: " + contact.EmailPhoneComplexProperty.Phone);
}
}