How to: Execute a Query that Returns PrimitiveType Results
This topic shows how to execute a command against a conceptual model by using an EntityCommand, and how to retrieve the PrimitiveType results by using an EntityDataReader.
To run the code in this example
-
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.
-
In the code page for your application, add the following using statements (Imports in Visual Basic):
Example
This example executes a query that returns a PrimitiveType result. If you pass the following query as an argument to the ExecutePrimitiveTypeQuery function, the function displays the average list price of all Products:
SELECT VALUE AVG(p.ListPrice) FROM AdventureWorksEntities.Products as p
If you pass a parameterized query, like the following, EntityParameter objects to the Parameters property on the EntityCommand object.
static void ExecutePrimitiveTypeQuery(string esqlQuery) { if (esqlQuery.Length == 0) { Console.WriteLine("The query string is empty."); return; } using (EntityConnection conn = new EntityConnection("name=AdventureWorksEntities")) { conn.Open(); // Create an EntityCommand. using (EntityCommand cmd = conn.CreateCommand()) { cmd.CommandText = esqlQuery; // Execute the command. using (EntityDataReader rdr = cmd.ExecuteReader(CommandBehavior.SequentialAccess)) { // Start reading results. while (rdr.Read()) { IExtendedDataRecord record = rdr as IExtendedDataRecord; // For PrimitiveType // the record contains exactly one field. int fieldIndex = 0; Console.WriteLine("Value: " + record.GetValue(fieldIndex)); } } } conn.Close(); } }