LINQ maintains all of its relationships between all the
related objects. Every primary and foreign key relationship contains an object
reference for that particular relationship. A PK reference is represented by an
EntityRef generic object, while an FK reference is a collection of objects in
an EntitySet generic collection.
Generally, LINQ-to-SQL works like most business objects you
would expect to; if you assign the reference for that property to the business
object, it retains that reference. However if you do not, it is null. Let me
explain. Let us say the data context has an Orders table. This Orders table is
related to the Customers table, where the Customer is the primary key. For an
order record in that table, which is represented by the Order business object,
this object has a Customer reference property and a CustomerKey GUID property.
If you assign a value to the CustomerKey, the Customer object
reference is not automatically populated; however, the reverse is not true. Whenever
an object reference is provided to the Customer property, the CustomerKey property
contains the GUID primary key value.
Once the call to the DataContext.SubmitChanges is made, the
value assigned to CustomerKey refreshes the value in the Customer object
reference property. Let us look at an example. Below a new order object is
created and a customer key is assigned.
Listing 1
Order order = new Order();
order.CustomerKey = customerKey;
Assert.IsNotNull(order.Customer); // is success
But, if using the opposite approach where an object is
assigned to the Customer property, the CustomerKey is populated.
Listing 2
Order order = new Order();
order.Customer = context.Customers.First();
Assert.IsTrue(order.CustomerKey != Guid.Empty); // is success
If you are updating your LINQ objects, and you want to
update an object without submitting the changes to the database at that moment,
you can make the assignment via an object reference, which will update the
relationship key.