New Posts New Posts RSS Feed: using the Context to CreateCommand and run sql
  FAQ FAQ  Forum Search   Calendar   Register Register  Login Login

using the Context to CreateCommand and run sql

 Post Reply Post Reply
Author
orcities View Drop Down
Senior Member
Senior Member
Avatar

Joined: 28-Aug-2007
Location: United States
Posts: 454
Post Options Post Options   Quote orcities Quote  Post ReplyReply Direct Link To This Post Topic: using the Context to CreateCommand and run sql
    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.
Back to Top
DenisK View Drop Down
IdeaBlade
IdeaBlade


Joined: 25-Aug-2010
Posts: 715
Post Options Post Options   Quote DenisK Quote  Post ReplyReply Direct Link To This Post 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();
      }
    }
Back to Top
 Post Reply Post Reply

Forum Jump Forum Permissions View Drop Down