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 (Entity Framework).

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

    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


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 conn As New EntityConnection("name=AdventureWorksEntities")
' Create a query that takes two parameters.
Dim esqlQuery As String = "SELECT VALUE Contact FROM AdventureWorksEntities.Contacts " & _
" AS Contact WHERE Contact.LastName = @ln AND Contact.FirstName = @fn"

Using cmd As New EntityCommand(esqlQuery, conn)
' Create two parameters and add them to
' the EntityCommand's Parameters collection
Dim param1 As New EntityParameter()
param1.ParameterName = "ln"
param1.Value = "Adams"
Dim param2 As New EntityParameter()
param2.ParameterName = "fn"
param2.Value = "Frances"


Using rdr As DbDataReader = cmd.ExecuteReader(CommandBehavior.SequentialAccess)
' Iterate through the collection of Contact items.
While rdr.Read()
End While
End Using
End Using
End Using

See Also

Build Date:

© 2014 Microsoft