Sunday, June 13, 2010

Entity Framework Querying 101

// The database tables are represented by object sets.
// These provide the basic CRUD operations on the table.
ObjectSet<Contact> objectSet = objectContext.Contacts;

// The object sets are themselves object queries.
// These provide support for queries written in Entity SQL.
ObjectQuery<Contact> objectQuery1 = objectContext.Contacts;

ObjectQuery<Contact> objectQuery2 = objectContext.Contacts
.Where("it.FirstName = 'Mathieu'");

ObjectQuery<Contact> objectQuery3 = objectContext.CreateQuery<Contact>(
"SELECT VALUE it FROM EntityContainer.Contacts AS it " +
"WHERE it.FirstName = @firstName");

objectQuery3.Parameters.Add(new ObjectParameter(
"firstName", "Mathieu"));

// The object queries finally implement IQueriable.
// This enables the use of Linq to Entities queries.
IQueryable<Contact> iQueryable1 = objectContext.Contacts;

IQueryable<Contact> iQueryable2 = objectContext.Contacts
.Where(contact => contact.FirstName == "Mathieu");

// All these techniques are equivalent ways to define a query,
// which won't actually be executed before it is enumerated.