HOW TO:使用 EntityCommand 執行參數化預存程序 (EntityClient)
本主題提供如何使用 EntityCommand 執行參數化預存程序的範例。這個範例使用 HOW TO:定義具有預存程序的模型 (Entity Framework) 中實作的預存程序和資料模型。如需設定專案的詳細資訊,以及如何使用物件服務執行預存程序的範例,請參閱 HOW TO:使用預存程序執行查詢 (Entity Framework)。
範例
以下程式碼會執行參數化預存程序,其中 SalesOrderHeaderId 是必要的參數。然後 EntityDataReader 將會讀取結果。
Using conn As EntityConnection = New EntityConnection("name=AdventureWorksEntities")
conn.Open()
Try
' Create an EntityCommand.
Using cmd As EntityCommand = conn.CreateCommand()
cmd.CommandText = "AdventureWorksEntities.GetOrderDetails"
cmd.CommandType = CommandType.StoredProcedure
Dim param As New EntityParameter()
param.Value = "43659"
param.ParameterName = "SalesOrderHeaderId"
cmd.Parameters.Add(param)
Using rdr As EntityDataReader = cmd.ExecuteReader(CommandBehavior.SequentialAccess)
Do While rdr.Read
' Read the results returned by the stored procedure.
Console.WriteLine("Header#: {0} " & _
"Order#: {1} ProductID: {2} Quantity: {3} Price: {4}", _
rdr.Item(0), rdr.Item(1), rdr.Item(2), rdr.Item(3), rdr.Item(4))
Loop
End Using
End Using
Catch ex As EntityException
Console.WriteLine(ex.ToString())
End Try
conn.Close()
End Using
using (EntityConnection conn =
new EntityConnection("name=AdventureWorksEntities"))
{
conn.Open();
try
{
// Create an EntityCommand.
using (EntityCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "AdventureWorksEntities.GetOrderDetails";
cmd.CommandType = CommandType.StoredProcedure;
EntityParameter param = new EntityParameter();
param.Value = "43659";
param.ParameterName = "SalesOrderHeaderId";
cmd.Parameters.Add(param);
// Execute the command.
using (EntityDataReader rdr =
cmd.ExecuteReader(CommandBehavior.SequentialAccess))
{
// Read the results returned by the stored procedure.
while (rdr.Read())
{
Console.WriteLine("Header#: {0} " +
"Order#: {1} ProductID: {2} Quantity: {3} Price: {4}",
rdr[0], rdr[1], rdr[2], rdr[3], rdr[4]);
}
}
}
}
catch (EntityException ex)
{
Console.WriteLine(ex.ToString());
}
conn.Close();
}