共用方式為


作法:使用 EntityCommand 執行參數化預存程序

本主題顯示如何使用 EntityCommand 類別,執行參數化預存程序。

執行此範例中的程式碼

  1. School 模型新增至您的專案,並設定專案使用 Entity Framework。 如需詳細資訊,請參閱操作說明:使用實體資料模型精靈

  2. 在應用程式的代碼頁中,新增下列 using 指示詞 (Imports 在 Visual Basic 中):

    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.Common;
    using System.Data.EntityClient;
    using System.Data.Metadata.Edm;
    
    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
    
    
  3. 匯入 GetStudentGrades 預存程序,並指定 CourseGrade 實體做為傳回型別。 如需如何匯入預存程序的資訊,請參閱操作說明:匯入預存程序

範例

下列程式碼會執行 GetStudentGrades 預存程序,其中 StudentId 是必要參數。 然後 EntityDataReader 會讀取結果。

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();
}
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

另請參閱