Print Page | Close Window

using the Context to CreateCommand and run sql

Printed From: IdeaBlade
Category: DevForce
Forum Name: DevForce 2010
Forum Discription: For .NET 4.0
URL: http://www.ideablade.com/forum/forum_posts.asp?TID=2153
Printed Date: 10-Jun-2026 at 7:09pm


Topic: using the Context to CreateCommand and run sql
Posted By: orcities
Subject: using the Context to CreateCommand and run sql
Date Posted: 13-Sep-2010 at 2:34pm
Is it possible to write straight sql and get results not dependent on know which type of entity is returned.
Similar to the following:
 
using(EntityConnection connection = new EntityConnection("Name = SchoolEntities"))
{
connection.Open();
EntityCommand entityCommand = connection.CreateCommand();
entityCommand.CommandText =
                  @"Select p.ProductID as Id from SchoolEntities.Product as p";
 
EntityDataReader entityDataReader =
entityCommand.ExecuteReader(CommandBehavior.SequentialAccess);
 
while (entityDataReader.Read())
{
              for (int i = 0; i < entityDataReader.FieldCount; i++)
              Console.Write(entityDataReader.ToString() + "\t");
              Console.WriteLine();
}
 
       connection.Close();
}
 
I don't want to have to create two Model just to perform this option that I need.



Replies:
Posted By: DenisK
Date Posted: 14-Sep-2010 at 2:56pm
Hi orcities;

It looks like it's possible. Here's my test code querying the NorthwindIB database.

public void UsingEntityConnectionWithDevForce() {
      string connectionString1 = 
        ConfigurationManager.ConnectionStrings["NorthwindIBEntityManager"].ConnectionString;

      string connectionString2 = "Name = NorthwindIBEntityManager";

      using (EntityConnection connection = new EntityConnection(connectionString2)) {
        connection.Open();

        EntityCommand entityCommand = connection.CreateCommand();
        entityCommand.CommandText = 
                    "Select emp.FirstName as First, emp.LastName as Last " +
                     "FROM NorthwindIBEntityManager.Employees AS emp";

        EntityDataReader reader = entityCommand.ExecuteReader(CommandBehavior.SequentialAccess);

        while (reader.Read()) {
          Output += String.Format("{0} {1} \n", reader["First"], reader["Last"]);
        }

        connection.Close();
      }
    }



Print Page | Close Window