方法: EntityCommand を使用してパラメーター化されたストアド プロシージャを実行する

このトピックでは、EntityCommand クラスを使用して、パラメーター化されたストアド プロシージャを実行する方法を示します。

この例のコードを実行するには

  1. School モデルをプロジェクトに追加し、Entity Framework が使用されるようにプロジェクトを構成します。 詳細については、Entity Data Model ウィザードを使用する」を参照してください。

  2. アプリケーションのコード ページで、次の using ステートメント (Visual Basic の場合は Imports) を追加します。

    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;
    
    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

関連項目