Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

LINQ to SQL Relationships

0.00/5 (No votes)
26 Jun 2008 1  
LINQ to SQL is an interesting Object-Relational Mapper because it remembers the relationships objects have between each other.  As usual, LINQ to SQL

This articles was originally at wiki.asp.net but has now been given a new home on CodeProject. Editing rights for this article has been set at Bronze or above, so please go in and edit and update this article to keep it fresh and relevant.

LINQ to SQL is an interesting Object-Relational Mapper because it remembers the relationships objects have between each other.  As usual, LINQ to SQL works like any ORM in that it has a designer that the developer can use to create the architecture that mimics the database structure.  LINQ to SQL manages the relationships one object has between the other.  For instance, whenever one object is added to a child collection of another, a PK/FK  relationship is established.  If, in another object, the application changes the primary key reference to something else, this change is made in the respective collections.

For instance, a Customer object has an EntitySet object (which is the type of object used to represent a child relationship) of Order objects.  The Customer is the PK in the database, and the Orders collection is the FK.  Anytime a new object is added to the Orders entity set, it's queued up to be inserted into the database, as well as being added to the collection.  So, in this way, LINQ to SQL manages the relationship between Customers and Orders.  This also works if you change the primary key reference to another object.  LINQ to SQL will transfer this object to the new parent's entity set collection.

When a new object is created, it doesn't immediately belong to the context.  For instance, look at this:

Order order = new Order();
order.Total = 19.99;
order.Date = DateTime.Now;

At this point, this object is independent and not a part of the context (it is not queued up for insertion).  Once you do:

customer.Orders.Add(order)

Where the customer object was retrieved from the database, this new order is queued for insertion and added as a relationship to the customer.  If you use an identity, the key value is set to zero, until you submit the changes (refreshed whenever the object is actually inserted).  At this point, relationships aren't validated; however, if there is a primary key/foreign key constraint error, this becomes known at the time SubmitChanges is called by a thrown exception.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here