Programming the Object Services Layer in Entity Framework

Leverage the Object Services Layer in ADO.Net Entity Framework to reduce the impedance mismatch between the object and data models in your application

object services layer

object services layer

An ORM (Object Relational Mapping) tool is one that is used to abstract the data access logic of your application. You can use ORM to bridge the apparent mismatch between the data and the object models. In this post, I will present a discussion on ORM and also a discussion on the Object Services Layer in Entity Framework.

What is an ORM? Why is it needed?

An application that is data centric can have two perspectives -- the data model and the object mode. The data model defines how the data is stored in the data store. The data store can be a relational database like SQL Server, Oracle, etc. On the contrary, the object model represents the application’s object oriented programming model. In using ORM tools, you can focus on the business logic of the application and you can store data in the database with much less code.

You can take advantage of an ORM to convert data between incompatible type systems - you can store your domain objects into the underlying database without having to worry about the internal intricacies on how the data is actually stored.

Let’s understand this with the help of an example. Consider the following code snippet that shows how you can retrieve data from the Employee table.

string queryString = "SELECT FirstName, LastName FROM Employee WHERE EmployeeID = 15";

    using (SqlConnection connection = new SqlConnection(connectionString))

    {

        SqlCommand sqlCommand = new SqlCommand(queryString, connection);

        connection.Open();

        SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();

        try

        {

            while (sqlDataReader.Read())

            {

                Console.WriteLine(String.Format("{0}, {1}", sqlDataReader[0], sqlDataReader[1]));

            }

        }

        finally

        {

            sqlDataReader.Close();

        }

    }

Now, if you are using an ORM you can simply write a few lines of code to retrieve data as shown in the code snippet below.

Repository repository = new Repository();

//Some code

Employee emp = repository.GetEmployee(15);

String firstName = p.FirstName;

String lastName = p.LastName;

The ADO.NET Entity Framework

Microsoft's Entity Framework is an extended ORM that helps you to isolate the object model of your application from the data model, i.e., from the way the data is actually stored and represented in the underlying database. You can use the Entity Framework to program against the object model in lieu of the data model and perform CRUD operations on top of it. With Entity Framework -- Microsoft's flagship data access platform, you can work with relational data using domain-specific objects.

The ADO.Net Entity Framework basically comprises of the following three layers:

  1. The Conceptual Layer or the C-Space Layer - Represented using CSDL (Conceptual Data Language)
  2. The C-S Mapping Layer – Represented MSL (Mapping Schema Language)
  3. The Logical or the Storage Layer (also called the S-Space) – Represented using SSDL (Store-specific Data Language)

You can query data exposed by the Entity Data Model in one of the following ways:

  1. EntityClient Provider using the Entity SQL
  2. Object Services Layer using ObjectQuery
  3. LINQ to Entities

The Object Services Layer

The ObjectServices layer fits between the EntityClient Provider and your query layer and provides most of the functionality of Entity Framework -- it provides most of the rich ORM features provided by Entity Framework. The Object Services Layer resides in the System.Data.Objects namespace in System.Data.Entity.dll assembly. The Object Services Layer provides a more generic approach towards working with data - it uses an Object Query instance to process the data internally and execute your queries.  

The official ADO.Net blog states: "One of the main features of the Entity Framework revolves around Object Services. The main points of Object services are to write less code and allow programmers to program against objects to access the data that’s stored in a database or possibly anywhere."

Note that the ObjectContext is the core of the Object Services Layer. To work with Object Services, you should include the System.Data.Objects and System.Data.Objects.DataClasses namespaces. The Object Services Layer provides the following benefits:

  1. Support for state management, optimistic concurrency and identity resolution
  2. Support for lazy loading, inheritance and navigation relationships
  3. Support for query transformation, materialization and change tracking

You can use the Object Services Layer to perform CRUD operations against the Entity Data Model.  The Object Services layer also provides support for querying data using Entity SQL and LINQ. Let’s dive into some code now.

The following code snippet shows how you can query data using Object Services.

using (NorthwindEntities context = new NorthwindEntities())

    {

        ObjectQuery<Products> products = context.CreateQuery<Products>("SELECT VALUE p FROM Products AS p");

        foreach (Products p in products)

        {

            Console.WriteLine(p.ProductName);

        }

    }

The following code snippet illustrates how you can add a record to the Employee table. 

using (var context = new PayrollContext())

            {

                Employee emp = new Employee {  EmployeeID = 1, FirstName = "Joydip", LastName = "Kanjilal" };

                context.Employees.Add(emp);

                context.SaveChanges();

            }

You can learn more on Entity Framework and Object Services Layer from this MSDN article.

This article is published as part of the IDG Contributor Network. Want to Join?

From CIO: 8 Free Online Courses to Grow Your Tech Skills
Notice to our Readers
We're now using social media to take your comments and feedback. Learn more about this here.