Share via


방법: EntityCommand를 사용하여 매개 변수가 있는 저장 프로시저 실행(EntityClient)

이 항목에서는 EntityCommand 클래스를 사용하여 매개 변수가 있는 저장 프로시저를 실행하는 방법을 보여 줍니다.

이 예제의 코드를 실행하려면

  1. 프로젝트에 School 모델을 추가하고 Entity Framework 를 사용하도록 프로젝트를 구성합니다. 자세한 내용은 방법: 엔터티 데이터 모델 마법사 사용(Entity Framework)을 참조하십시오.

  2. 응용 프로그램의 코드 페이지에서 다음 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;
    
  3. GetStudentGrades 저장 프로시저를 가져오고 CourseGrade 엔터티를 반환 형식으로 지정합니다. 저장 프로시저를 가져오는 방법은 How to: Import Stored Procedures를 참조하십시오.

예제

다음 코드에서는 StudentId가 필수 매개 변수인 GetStudentGrades 저장 프로시저를 실행합니다. 그런 다음 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();
}

참고 항목

개념

Entity Framework용 EntityClient 공급자