このトピックでは、EntityCommand を使用して、パラメータ化されたストアド プロシージャを実行する方法の例を示します。この例では、「ストアド プロシージャを使用してモデルを定義する方法 (Entity Framework)」で実装されたストアド プロシージャとデータ モデルを使用します。プロジェクトの構成の詳細と、Object Services を使用したストアド プロシージャの実行方法の例については、「ストアド プロシージャを使用してクエリを実行する方法 (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();
}