Freigeben über


ObjectSet vs ObjectQuery in Entity Framework v 4

I was a little curious about this change in EFv4 and wanted to understand why this was done. So here is what I was able to understand

Background

Lets take a look at the following code for querying the EntitySet in EF v3.5

  using (NorthwindEntities ex = new NorthwindEntities())

            {

                var cus = ex.Customers;

                foreach (var c in cus)

                {

                    //do some operation here             

                }

            }

If you put a break point inside the foreach block and try to inspect the cus type you will see the following type listed in EF v3.5

file

As you see here the type resolved is ObjectQuery<NorthwindModel.Customers>. And the major design hit was that if you were to do some CUD(Create,Update and Delete) operation in the pre EF v4 world, you had to depend upon ObjectContext rather than perfoming them on the Object itself. So we had to write the following code for the Create operation


 //create a new customer      
<br>Customers newCustomer = new Customers();    
<br> newCustomer.ContactName = "Xyz";       
<br> //fill the rest details of the customer
<br> //...   
<br>//add the new customer to the context  
<br> ex.AddToCustomers(newCustomer); 
<br>//persist changes 
<br> ex.SaveChanges();
 

Outcome

In EFv4, ObjectSet was introduced. ObjectSet is an extension to ObjectQuery and has the following graph of inheritance

ObjectSetClass 

This gives power to the EntitySet to do the CUD operations that were only available in the ObjectContext before. So now the above code for adding a Customer entity will look like this

  using (NorthwindEntities ex = new NorthwindEntities())            

 {              

 Customer newCustomer = new Customer();

 newCustomer.ContactName = "Xyz";       

 ex.Customers.AddObject(newCustomer);  

 ex.SaveChanges();       

 }