Export (0) Print
Expand All

How to: Execute a Parameterized Entity SQL Query Using EntityCommand

This topic shows how to execute an Entity SQL query that has parameters by using an EntityCommand object.

To run the code in this example

  1. Add the AdventureWorks Sales Model to your project and configure your project to use the Entity Framework. For more information, see How to: Use the Entity Data Model Wizard.

  2. In the code page for your application, add the following using statements (Imports in Visual Basic):

    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;
    
    

Example

The following example shows how to construct a query string with two parameters. It then creates an EntityCommand, adds two parameters to the EntityParameter collection of that EntityCommand, and iterates through the collection of Contact items.

using (EntityConnection conn =
    new EntityConnection("name=AdventureWorksEntities"))
{
    conn.Open();
    // Create a query that takes two parameters.
    string esqlQuery =
        @"SELECT VALUE Contact FROM AdventureWorksEntities.Contacts 
                    AS Contact WHERE Contact.LastName = @ln AND
                    Contact.FirstName = @fn";

    using (EntityCommand cmd = new EntityCommand(esqlQuery, conn))
    {
        // Create two parameters and add them to 
        // the EntityCommand's Parameters collection 
        EntityParameter param1 = new EntityParameter();
        param1.ParameterName = "ln";
        param1.Value = "Adams";
        EntityParameter param2 = new EntityParameter();
        param2.ParameterName = "fn";
        param2.Value = "Frances";

        cmd.Parameters.Add(param1);
        cmd.Parameters.Add(param2);

        using (DbDataReader rdr = cmd.ExecuteReader(CommandBehavior.SequentialAccess))
        {
            // Iterate through the collection of Contact items.
            while (rdr.Read())
            {
                Console.WriteLine(rdr["FirstName"]);
                Console.WriteLine(rdr["LastName"]);
            }
        }
    }
    conn.Close();
}

See Also

Community Additions

ADD
Show:
© 2014 Microsoft