parameterized objectquery against a entity data model


What is an ObjectQuery ?
ObjectQuery is a class which is used to construct and execute queries against a Entity data model. Once the ObjectQuery has been executed, the results are returned as ObjectQuery<T>.

A parameterized ObjectQuery is an ObjectQuery with parameters. Adding parameters to queries makes the query more powerful. We can add parameters to the ObjectQuery after we instantiate the Object Query.

The statement
ObjectQuery Customers = new ObjectQuery(querystring,context);

Creates a new ObjectQuery instance using the Entity SQL query which is given below. The code below displays Customer ID of the selected customer named "Vam".

We know that this query returns an ObjectQuery objects. So, instead of writing a query with var keyword, we explicitly declared the type in the query.

We need to add parameters to the ObjectQuery prior to the execution. To work with ObjectQuery class, we need to add the System.Data.Objects namespace.

We also need to pass the ObjectContext as a parameter when we instantiate an Objectquery.
 
using (var context = new SalesOrderManagementEntities())
{
	string querystring = "SELECT VALUE Customer 
    FROM SalesOrderManagementEntities.Customer AS Customer 
    Where Customer.Name=@Name";
	ObjectQuery Customers = 
        new ObjectQuery(querystring,context);
	Customers.Parameters.Add(new ObjectParameter("Name", "Vam"));
	foreach (Customer result in Customers)
	Console.WriteLine(String.Format("{0} {1}",
	result.Name, result.CustomerId));
}