devxlogo

Working with Object Context in the ADO.NET Entity Framework

Working with Object Context in the ADO.NET Entity Framework

The ADO.NET Entity Framework is an extended object relational mapping (ORM) tool from Microsoft that has become increasingly popular over the past few years and is widely used these days. Microsoft designed the ADO.NET Entity Framework to objectify an application’s data and simplify the development of data-aware applications. Version 4.0 of the ADO.NET Entity Framework ships with Microsoft Visual Studio 2010 and offers a lot of new and enhanced features.

This article explains the basics of ADO.NET Entity Framework and shows how you can write programs that leverage the generic Object Context.

The Basics of ADO.NET Entity Framework

The first question that comes to one’s mind is “What is the ADO.NET Entity Framework?” What is it all about? Well, the ADO.NET Entity Framework (or Entity Framework, as it is popularly called) is an extended ORM development tool from Microsoft that helps you abstract the object model of an application from its relational or logical model. According to MSDN, “The ADO.NET Entity Framework enables developers to create data access applications by programming against a conceptual application model instead of programming directly against a relational storage schema. The goal is to decrease the amount of code and maintenance required for data-oriented applications.”

The Entity Framework is comprised of three layers:

  • The Conceptual Layer: Represented using CSDL (Conceptual Data Language)
  • The Storage Layer: Represented using SSDL (Store-specific Data Language)
  • The Mapping Layer: Represented MSL (Mapping Schema Language)

You can use any one of the following to query data exposed by the Entity Data Model, based on its entity relationship model.

  • LINQ to entities
  • The entity client
  • Object services

The primary goal of the Entity Framework was to raise the level of abstraction and simplify development of data-aware applications with reduced effort and reduced KLOC.

Working with the Object Context

The Object Context in Entity Framework (like as in LINQ to SQL) is the gateway to execute your queries against the Entity Data Model. Any object that is returned as a result of a query execution is attached to the Object Context. The Object Context can in turn track changes to the object and also persist the object to the data store.

The Object Context interacts with the database and abstracts the way the connection string, the connection to the underlying database, the queries, and the stored procedures are executed. It also manages reads and writes to and from the database.

The Object Context uses the ObjectStateManager to manage the state changes of objects and then applies those changes to the underlying data store appropriately. The Object Context in Entity Framework is represented by the class called ObjectContext.

CRUD Operations Using the ObjectContext

You can use the Object Context to perform CRUD operations on your data exposed by the Entity Data Model. Here’s how:

  1. Create the record

    Let’s create an employee record, as an example:

    PayrollEntities dataContext = new PayrollEntities();try{  Employee emp = new Employee   {     EmployeeID = 1,     FirstName = "Joydip",     LastName = "Kanjilal",     Address = "Kolkata"   };dataContext.Employees.AddObject(emp);dataContext.SaveChanges();}catch{  //Write your code here to handle errors.}
  2. Update record

    To modify the employee record, you can use the following code:

    PayrollEntities dataContext = new PayrollEntities();try{  Employee emp = dataContext.Employees.First(e=>e.EmployeeID == 1);  emp.Address = "Hyderabad";  dataContext.SaveChanges();}catch{  //Write your code here to handle errors.}
  3. Delete record

    To delete the employee record, you can use the following code:

    PayrollEntities dataContext = new PayrollEntities();try{  Employee emp = dataContext.Employees.First(e=>e.EmployeeID == 1);  dataContext.DeleteObject(emp);  dataContext.SaveChanges();}catch{  //Write your code here to handle errors.}

In the next section, you will explore how to query data exposed by the Entity Data Model using Object Context.

Querying the Entity Data Model Using Object Context

The following code snippet illustrate how you can use your Object Context instance to query data exposed by the Entity Data Model.

using (var  dataContext = new NorthwindEntities())   {       var Customers = from c in dataContext.Customer select c;         foreach (var Customer in Customers)      {          Console.WriteLine(String.Format("{0} {1}",          Customer.Name, Customer.Address ));      }   }

Attaching and Detaching Objects from the Object Context

You can attach or detach objects to and from the Object Context using methods such as, Attach() or Detach(). To attach a previously detached object to the Object Context, you can use the following code:

using (NorthwindEntities dataContext = new NorthwindEntities()){   dataContext.Attach(employeeObj);}

To detach objects from the ObjectContext you can use the System.Data.Objects.ObjectSet.Detach() method or the System.Data.Objects.ObjectContext.Detach(System.Object) method.

You can also specify the entity to be detached as follows:

dataContext.Entry(entity).State = EntityState.Detached;

To check if an entity is already detached, you can use this code.

if (entity == null || entity.EntityState != EntityState.Detached)Console.WriteLine("Entity is null or already detached.");

Creating a Shared Object Context

The following code snippet illustrates how you can create a shared Object Context so that it can be globally shared amongst all classes in the application. This is not suitable for ASP.NET applications though.

private static AdventureWorksObjectContext _objectContext;public AdventureWorksObjectContext ObjectContext{    get    {        if (_objectContext == null)            _objectContext = new AdventureWorksObjectContext();        return _objectContext;    }}

Summary

ADO.NET Entity Framework 4.0 is a more mature ORM tool than its predecessors. The new and enhanced features in Entity Framework 4 include, POCO support, Code First Development, Self Tracking Entities, better testability, improved LINQ operator support, improved lazy loading support, and many others. In this article you explored the Object Context in Entity Framework.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist