如何:使用 EntityCommand 执行参数化存储过程

本主题说明如何使用 EntityCommand 类执行参数化存储过程。

运行本示例中的代码

  1. 学校模型添加到项目,并将项目配置为使用实体框架。 有关详细信息,请参阅如何:使用实体数据模型向导

  2. 在应用程序的代码页中,添加以下 using 指令(在 Visual Basic 中为 Imports):

    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

请参阅