querying entity data model using objectcontext


The ObjectContext is the main class in the Entity Framework which interacts with the database. The ObjectContext maintains the connection to the database and also manages all the read and write operations.

Entity Data Model can be queried using Linq to Entities or by Entity Sql or by Linq methods. Whichever the query method, results are always returned as objects. All the objects returned by a query are attached to an ObjectContext.

Using the ObjectStateManager, the ObjectContext tracks the changes to the objects and applies the changes to the data store. The ObjectStateManager holds the references of all the objects. When a transaction occurs, the ObjectContext keeps track of the order of operations and generates SQL to execute the operations efficiently.

When we query an object with the ObjectContext, information about the object is stored in the ObjectContext state manager. And, when we call SaveChanges() method of the ObjectContext, the ObjectContext looks for all the objects in the ObjectStateManager and does appropriate actions on each object.

Querying EDM using ObjectContext
In the code given below, we retrieve all the customers using LINQ to Entities query using c#.

class Program
{
	static void Main(string[] args)
	{
		using (var context = new SalesOrderManagementEntities())
		{
			var Customers = from c in context.Customer
                         	select c;
			foreach (var Customer in Customers)
			{
 				Console.WriteLine(String.Format("{0} {1}",
 				Customer.Name, Customer.Address ));
			}
			Console.WriteLine();
			Console.ReadLine();
		}
	}
}

The SalesOrderManagementEntities is a class inherited from the ObjectContext. SalesOrderManagementEntities represents EntityContainer.

SalesOrderManagementEntities class has the property customer which is a EntitySet in the Entity Data Model.

In the LINQ query given above, we have used ObjectContext class's property Customer to get data from the Customer table. The result of above query are objects and are automatically attached to the ObjectContext.

Attaching and detaching objects from the ObjectContext
Attaching and detaching can be done either by calling methods such as add, attach, or detach or using the functionality of entity framework. The below code demonstrates how to attach an object to the ObjectContext.

using (var context = new SalesOrderManagementEntities())
{
  Customer customerdelete = new Customer { CustomerId = 1 };
  context.AttachTo("Customer", customerdelete);
  context.DeleteObject(customerdelete);
  context.SaveChanges();     
}