HOW TO:執行可傳回複雜類型的查詢 (EntityClient)
本主題示範如何使用 EntityCommand 來執行可傳回複雜類型的 實體 SQL 查詢。此範例使用 HOW TO:定義具有複雜類型的模型 (Entity Framework) 中所定義的結構描述。如需設定專案的詳細資訊,以及如何使用物件服務來執行可傳回複雜類型之查詢的範例,請參閱 HOW TO:使用複雜類型來建立和執行物件查詢 (Entity Framework)。
範例
下列範例示範如何建立及執行具有複雜類型的查詢。複雜類型代表包含類似實體類型的屬性集、但不包含索引鍵屬性的型別。下列 CCustomer 實體的 Address 屬性會實作成複雜類型。下列範例會輸出 CCustomer 型別的兩個屬性:CustomerId 和 Address。由於 Address 是複雜類型,所以程式碼會輸出 Address 的屬性值。
Using conn As EntityConnection = New EntityConnection("name=CustomerComplexAddrContext")
conn.Open()
' Create an EntityCommand.
Using cmd As EntityCommand = conn.CreateCommand()
' Create a query that returns Address complex type.
Dim esqlQuery As String = "SELECT VALUE customers FROM " & _
"CustomerComplexAddrContext.CCustomers " & _
"AS customers WHERE customers.CustomerId < 3"
cmd.CommandText = esqlQuery
' Execute the command.
Using rdr As EntityDataReader = cmd.ExecuteReader(CommandBehavior.SequentialAccess)
' The result returned by this query contains
' Address complex Types.
Do While rdr.Read
' Display CustomerID
Console.WriteLine("Customer ID: {0}", _
rdr.Item("CustomerId"))
' Display Address information.
Dim nestedRecord As DbDataRecord = DirectCast(rdr.Item("Address"), DbDataRecord)
Console.WriteLine("Address:")
For i = 0 To nestedRecord.FieldCount - 1
Console.WriteLine(" " + nestedRecord.GetName(i) & _
": " + nestedRecord.GetValue(i))
Next i
Loop
End Using
End Using
conn.Close()
End Using
using (EntityConnection conn =
new EntityConnection("name=CustomerComplexAddrContext"))
{
conn.Open();
// Create a query that returns Address complex type.
string esqlQuery =
@"SELECT VALUE customers FROM
CustomerComplexAddrContext.CCustomers
AS customers WHERE customers.CustomerId < 3";
try
{
// Create an EntityCommand.
using (EntityCommand cmd = conn.CreateCommand())
{
cmd.CommandText = esqlQuery;
// 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("Customer ID: {0}",
rdr["CustomerId"]);
// Display Address information.
DbDataRecord nestedRecord =
rdr["Address"] as DbDataRecord;
Console.WriteLine("Address:");
for (int i = 0; i < nestedRecord.FieldCount; i++)
{
Console.WriteLine(" " + nestedRecord.GetName(i) +
": " + nestedRecord.GetValue(i));
}
}
}
}
}
catch (EntityException ex)
{
Console.WriteLine(ex.ToString());
}
conn.Close();
}