Database Reference
In-Depth Information
Figure 3-5. A model with a Customer entity
To query the model using Entity SQL (eSQL), a dialect of SQL implemented by Entity Framework, follow the
pattern in Listing 3-8. Keep in mind that when querying the underlying data store, you should favor LINQ-to-Entity
queries over eSQL, due to feature-rich and strong-typing experience that LINQ provides. Entity SQL gives you the
flexibility to construct database queries dynamically against the entity data model.
Listing 3-8. Executing an Entity SQL Statement Using Both Object Services and EntityClient
using (var context = new EFRecipesEntities())
{
// delete previous test data
context.Database.ExecuteSqlCommand("delete from chapter3.customer"); // add new
test data
var cus1 = new Customer { Name = "Robert Stevens",
Email = " rstevens@mymail.com " };
var cus2 = new Customer { Name = "Julia Kerns",
Email = " julia.kerns@abc.com " };
var cus3 = new Customer { Name = "Nancy Whitrock",
Email = " nrock@myworld.com " };
context.Customers.Add(cus1);
context.Customers.Add(cus2);
context.Customers.Add(cus3);
context.SaveChanges();
}
// using object services from ObjectContext object
using (var context = new EFRecipesEntities())
{
Console.WriteLine("Querying Customers with eSQL Leveraging Object Services...");
String esql = "select value c from Customers as c";
// cast the DbContext to the underlying ObjectContext, as DbContext does not
// provide direct support for EntitySQL queries
var customers = ((IObjectContextAdapter)context).ObjectContext.CreateQuery<Customer>(esql);
Foreach (var customer in customers)
{
Console.WriteLine ("{0}'s email is: {1}",
customer.Name, customer.Email);
}
}
 
Search WWH ::




Custom Search