Jun 8, 2009

Entity Framework stack

The Entity Framework's most prominent feature set and that which you are likely to work with most often is referred to as Object Services. Object Services sits on top of the Entity Framework stack, and provides all the functionality needed to work with objects that are based on your entities. Object Services provides a class called EntityObject and can manage any class that inherits from EntityObject. This includes materializing objects from the results of queries against the EDM, keeping track of changes to those objects, managing relationships between objects, and saving changes back to the database.

EntityClient is the other major API in the Entity Framework. It provides the functionality necessary for working with the store queries and commands (in conjunction with the database provider) connecting to the database, executing the commands, retrieving the results from the store, and reshaping the results to match the EDM.

You can work with EntityClient directly or work with Object Services, which sits on top of EntityClient. EntityClient is only able to perform queries, and it does this on behalf of Object Services. The difference is that when you work directly with EntityClient, you will get tabular results (though the results can be shaped). If you are working with Object Services, it will transform the tabular data created by EntityClient into objects.

The tabular data returned by EntityClient is read-only. Only Object Services provides change tracking and the ability to save changes back to the data store.

Object Services' core object is ObjectContext and ObjectQuery. ObjectContext is like a strongly type entity storage. ObjectQuery is used to retrieve the Entity from ObjectContext. ObjectQuery implements the linq feature, it implments interface, IQueryable, and IEnumberable.

using (AdventureWorksEntities advWorksContext =
    new AdventureWorksEntities())
        // Define an ObjectQuery to use with the LINQ query.
        ObjectQuery products = advWorksContext.Product;

        // Define a LINQ query that returns a selected product.
        var result = from product in products 
                     where product.ProductID == 900
                     select product;

        // Cast the inferred type var to an ObjectQuery
        // and then write the store commands for the query.
    catch (EntitySqlException ex)

The ObjectQuery is the core of Linq to Entity Framework, it will convert the query into Entity SQL, and send it the EntityClient. You can also ask ObjectContext create a ObjectQuery by write write Entity Sql, but eventually the Entity Sql will be executed by the EntityClient. EntityClient will convert the Entity Sql to native sql for the data provider below. Here is some sample code.

var qStr = @"SELECT VALUE c 
            FROM PEF.Contacts AS c 
            WHERE c.FirstName='Robert'";

var contacts = context.CreateQuery<Contact>(qStr);