Export (0) Print
Expand All

How to: Execute a Query that Returns PrimitiveType Results (EntityClient)

This topic provides an example of how to execute a command against an Entity Data Model (EDM) by using EntityCommand, and retrieve the PrimitiveType results by using 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. To do this, do one of the following:

  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 AdventureWorksModel;
    using System.Data.Metadata.Edm;
    
    

Example

To test the code, pass the following query as an argument to the ExecutePrimitiveTypeQuery function:

"SELECT VALUE AVG(p.ListPrice) FROM AdventureWorksEntities.Product as p"

The query above returns the PrimitiveType result.

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

        try
        {
            // 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));
                    }
                }
            }
        }
        catch (EntityException ex)
        {
            Console.WriteLine(ex.ToString());
        }
        conn.Close();
    }
}

See Also

Community Additions

Show:
© 2014 Microsoft