Database Reference
In-Depth Information
Console.WriteLine();
// using EntityClient
using (var conn = new EntityConnection("name=EFRecipesEntities"))
{
Console.WriteLine("Querying Customers with eSQL Leveraging Entity Client...");
var cmd = conn.CreateCommand();
conn.Open();
cmd.CommandText = "select value c from EFRecipesEntities.Customers as c";
using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess))
{
while (reader.Read())
{
Console.WriteLine("{0}'s email is: {1}",
reader.GetString(1), reader.GetString(2));
}
}
}
Following is the output from the code in Listing 3-8:
Querying Customers with eSQL Leveraging Object Services...
Robert Stevens's email is: rstevens@mymail.com
Julia Kerns's email is: julia.kerns@abc.com
Nancy Whitrock's email is: nrock@myworld.com
Customers Customers with eSQL Leveraging Entity Client...
Robert Stevens's email is: rstevens@mymail.com
Julia Kerns's email is: julia.kerns@abc.com
Nancy Whitrock's email is: nrock@myworld.com
How It Works
In Listing 3-8, we start by removing previous test data from the database. Then we create three customers, add them to
the context object, and call SaveChanges() to insert them into the database.
With customers in the database, we demonstrate two different approaches to retrieving them using Entity SQL. In
the first approach, we use the CreateQuery() method exposed by the legacy object context to create an ObjectQuery
object . Note how we cast the DbContext to an ObjectContextAdapter type to get to its underlying ObjectContext type
(keep in mind the newer DbContext wraps the older ObjectContext to improve the developer experience). We do so as
the DbContext does not provide direct support for eSQL queries. Note as well how we assign the Customer class type
to the generic placeholder value for CreateQuery() and pass in the eSQL query as a parameter. As we iterate over the
customers collection, the query is executed against the database and the resulting collection is printed to the console.
Because each element in the collection is an instance of our Customer entity type, we can use the properties of the
Customer entity type to gain strongly typed usage.
In the second approach, we use the EntityClient libraries in a pattern that is very similar to how we would use
SqlClient or any of the other client providers in ADO.NET. We start by creating a connection to the database. With the
connection in hand, we create a command object and open the connection. Next we initialize the command object
with the text of the Entity SQL statement we want to execute. We execute the command using ExecuteReader() and
obtain an EntityDataReader , which is a type of the familiar DbDataReader . We iterate over the resulting collection
using the Read () method.
 
 
Search WWH ::




Custom Search