本主题提供的示例演示如何使用 EntityCommand 执行参数化存储过程。此示例使用如何:使用存储过程定义模型(实体框架)中实现的存储过程和数据模型。有关配置项目的信息以及如何使用对象服务执行存储过程的示例,请参见如何:使用存储过程执行查询(实体框架)。
示例
下面的代码运行一个参数化存储过程,其中的 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();
}