Databases Reference
In-Depth Information
List<Product> products = query.ToList();
foreach (Product p in products)
Console.WriteLine(p.ProductName);
Object Identity
A crucial difference exists between Entity Framework and classic ADO.NET in the way they
handle rows retrieved from the database. Where ADO.NET treats the rows as values , Entity
Framework treats them as objects , so if a particular table row is returned by two different
queries, they return the same .NET object. The following code illustrates this example by
retrieving the same Product by ProductName and by ProductID :
Product chai1 = (from p in context.Products
where p.ProductName == “Chai”
select p).First();
Product chai2 = (from p in context.Products
where p.ProductID == 1
select p).First();
if (object.ReferenceEquals(chai1, chai2))
Console.WriteLine(“chai1 and chai2 are the same object”);
This behavior is different from the classic ADO.NET where you would get two different
DataRow objects that held the same field values. To implement this functionality, the
ObjectContext keeps track of all objects materialized from the data returned by queries,
and if a new query returns data for which an object already exists in the context, that
object is used and the newly returned data is discarded. Although this might seem coun-
terintuitive from the database point of view (if the Chai product record changed between
two queries, isn't it logical to see the new values?), this is actually consistent with a behav-
ior you would intuitively expect from a .NET object. Consider the following example:
Product chai = (from p in context.Products
where p.ProductName == “Chai”
select p).First();
chai.UnitsInStock += 50;
List<Product> allProducts = (from p in context.Products
select p).ToList();
Console.WriteLine(chai.UnitsInStock);
Here, the code modifies the number of units in stock for the Chai product object and then
executes another query that happens to retrieve it again. Because the code holds a refer-
ence to the Chai in a local variable, you would not expect an “unrelated” operation to
change its UnitsInStock property; the Entity Framework implements this behavior.
 
Search WWH ::




Custom Search