HOW TO:使用 EntityCommand 執行參數化預存程序 (EntityClient)
本主題顯示如何使用 EntityCommand 類別,執行參數化預存程序。
執行此範例中的程式碼
將 School 模型加入至專案中,並將專案設定為使用 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;
匯入
GetStudentGrades
預存程序,並指定CourseGrade
實體做為傳回型別。 如需關於如何匯入預存程序的詳細資訊,請參閱 How to: Import Stored Procedures。
範例
下列程式碼會執行 GetStudentGrades 預存程序,其中 StudentId 是必要參數。 然後 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();
}