HOW TO:執行可傳回 PrimitiveType 結果的查詢 (EntityClient)
本主題顯示如何使用 EntityCommand,針對概念模型執行命令,以及如何使用 EntityDataReader 擷取 PrimitiveType 結果。
執行此範例中的程式碼
將 AdventureWorks 銷售模型 加入至專案中,並將專案設定為使用 Entity Framework 。 如需詳細資訊,請參閱 HOW TO:使用實體資料模型精靈 (Entity Framework)。
在應用程式的字碼頁中加入下列 using 陳述式 (在 Visual Basic 中為 Imports):
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;
範例
此範例會執行傳回 PrimitiveType 結果的查詢。 如果您將下列查詢當做引數傳遞至 ExecutePrimitiveTypeQuery
函式,則函式會顯示所有 Products 的平均清單價格:
SELECT VALUE AVG(p.ListPrice) FROM AdventureWorksEntities.Products as p
如果您傳遞了參數型查詢 (類似下列查詢),請將 EntityParameter 物件加入至 EntityCommand 物件的 Parameters 屬性。
CASE WHEN AVG({@score1,@score2,@score3}) < @total THEN TRUE ELSE FALSE END
Private Shared Sub ExecutePrimitiveTypeQuery(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()
Dim record As IExtendedDataRecord = TryCast(rdr, IExtendedDataRecord)
' For PrimitiveType
' the record contains exactly one field.
Dim fieldIndex As Integer = 0
Console.WriteLine("Value: " & record.GetValue(fieldIndex))
End While
End Using
End Using
conn.Close()
End Using
End Sub
static void ExecutePrimitiveTypeQuery(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())
{
IExtendedDataRecord record = rdr as IExtendedDataRecord;
// For PrimitiveType
// the record contains exactly one field.
int fieldIndex = 0;
Console.WriteLine("Value: " + record.GetValue(fieldIndex));
}
}
}
conn.Close();
}
}