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

    
    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
        
    

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
    

Private Shared Sub ExecutePrimitiveTypeQuery(ByVal esqlQuery As String)
If esqlQuery.Length = 0 Then
Console.WriteLine("The query string is empty.")
Exit Sub
End If

Using conn As New EntityConnection("name=AdventureWorksEntities")
conn.Open()

' Create an EntityCommand.
Using cmd As EntityCommand = conn.CreateCommand()
cmd.CommandText = esqlQuery
' Execute the command.
Using rdr As EntityDataReader = cmd.ExecuteReader(CommandBehavior.SequentialAccess)
' Start reading results.
While rdr.Read()
Dim record As IExtendedDataRecord = TryCast(rdr, IExtendedDataRecord)
' For PrimitiveType
' the record contains exactly one field.
Dim fieldIndex As Integer = 0
Console.WriteLine("Value: " & record.GetValue(fieldIndex))
End While
End Using
End Using
conn.Close()
End Using
End Sub
    

See Also




Build Date:

2012-08-02
Show:
© 2014 Microsoft