LINQ To SQL Samples - Object IdentityOn This Page |
This sample demonstrates how, upon executing the same query twice, you will receive a reference to the same object in memory each time.
Public Sub LinqToSqlObjectIdentity01()
Dim cust1 As Customer = db.Customers.First(Function(c) c.CustomerID = "BONAP")
Dim cust2 As Customer = (From c In db.Customers _
Where c.CustomerID = "BONAP" _
Select c).First()
Console.WriteLine("cust1 and cust2 refer to the same object in memory: {0}", _
Object.ReferenceEquals(cust1, cust2))
End Sub
Result:
cust1 and cust2 refer to the same object in memory: True
This sample demonstrates how, upon executing different queries that return the same row from the database, you will receive a reference to the same object in memory each time.
Public Sub LinqToSqlObjectIdentity02()
Dim cust1 As Customer = db.Customers.First(Function(c) c.CustomerID = "BONAP")
Dim cust2 As Customer = (From o In db.Orders _
Where o.Customer.CustomerID = "BONAP" _
Select o).First().Customer
Console.WriteLine("cust1 and cust2 refer to the same object in memory: {0}", _
Object.ReferenceEquals(cust1, cust2))
End Sub
Result:
cust1 and cust2 refer to the same object in memory: True