How to: Execute a Parameterized Stored Procedure Using EntityCommand (EntityClient)

This topic provides an example of how to execute a parameterized stored procedure using EntityCommand. This example uses the stored procedure and data model implemented in How to: Define a Model with a Stored Procedure (Entity Framework). For information about configuring your project, and an example of how to execute a stored procedure using Object Services, see How to: Execute a Query Using a Stored Procedure (Entity Framework).

Example

The following code runs a parameterized stored procedure where SalesOrderHeaderId is a required parameter. The results are then read by EntityDataReader.

using (EntityConnection conn =
    new EntityConnection("name=AdventureWorksEntities"))
{
    conn.Open();
    try
    {
        // Create an EntityCommand.
        using (EntityCommand cmd = conn.CreateCommand())
        {
            cmd.CommandText = "AdventureWorksEntities.GetOrderDetails";
            cmd.CommandType = CommandType.StoredProcedure;
            EntityParameter param = new EntityParameter();
            param.Value = "43659";
            param.ParameterName = "SalesOrderHeaderId";
            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("Header#: {0} " +
                    "Order#: {1} ProductID: {2} Quantity: {3} Price: {4}",
                    rdr[0], rdr[1], rdr[2], rdr[3], rdr[4]);
                }
            }
        }
    }
    catch (EntityException ex)
    {
        Console.WriteLine(ex.ToString());
    }
    conn.Close();
}

See Also

Community Additions

Show: