How to: Execute a Parameterized Stored Procedure Using EntityCommand
This topic shows how to execute a parameterized stored procedure by using the EntityCommand class.
To run the code in this example
Add the School Model to your project and configure your project to use the Entity Framework. For more information, see How to: Use the Entity Data Model Wizard.
In the code page for your application, add the following using statements (Imports in Visual Basic):
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;
Import the
GetStudentGrades
stored procedure and specifyCourseGrade
entities as a return type. For information on how to import a stored procedure, see How to: Import Stored Procedures.
Example
The following code executes the GetStudentGrades stored procedure where StudentId is a required parameter. The results are then read by an EntityDataReader.
Using conn As New EntityConnection("name=SchoolEntities")
conn.Open()
' Create an EntityCommand.
Using cmd As EntityCommand = conn.CreateCommand()
cmd.CommandText = "SchoolEntities.GetStudentGrades"
cmd.CommandType = CommandType.StoredProcedure
Dim param As New EntityParameter()
param.Value = 2
param.ParameterName = "StudentID"
cmd.Parameters.Add(param)
' Execute the command.
Using rdr As EntityDataReader = cmd.ExecuteReader(CommandBehavior.SequentialAccess)
' Read the results returned by the stored procedure.
While rdr.Read()
Console.WriteLine("ID: {0} Grade: {1}", rdr("StudentID"), rdr("Grade"))
End While
End Using
End Using
conn.Close()
End Using
using (EntityConnection conn =
new EntityConnection("name=SchoolEntities"))
{
conn.Open();
// Create an EntityCommand.
using (EntityCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "SchoolEntities.GetStudentGrades";
cmd.CommandType = CommandType.StoredProcedure;
EntityParameter param = new EntityParameter();
param.Value = 2;
param.ParameterName = "StudentID";
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("ID: {0} Grade: {1}", rdr["StudentID"], rdr["Grade"]);
}
}
}
conn.Close();
}