Export (0) Print
Expand All

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

  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):

    
    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

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.


CASE WHEN AVG({@score1,@score2,@score3}) < @total THEN TRUE ELSE FALSE END
    

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();
}
}
    

See Also




Build Date:

2012-08-02
Show:
© 2014 Microsoft