LINQ to SQL (Part 4 - Updating our Database)
page 5 of 12
by Scott Guthrie
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 10593/ 398

Updates across Relationships

What makes O/R mappers like LINQ to SQL extremely flexible is that they enable us to easily model cross-table relationships across our data model.  For example, I can model each Product to be in a Category, each Order to contain OrderDetails for line-items, associate each OrderDetail line-item with a Product, and have each Customer contain an associated set of Orders.  I covered how to construct and model these relationships in Part 2 of this blog series.

LINQ to SQL enables me to take advantage of these relationships for both querying and updating my data. For example, I could write the below code to create a new Product and associate it with an existing "Beverages" category in my database like so:

Figure 8

Note above how I'm adding the Product object into the Category's Products collection.  This will indicate that there is a relationship between the two objects, and cause LINQ to SQL to automatically maintain the foreign-key/primary key relationship between the two when I call "SubmitChanges()".

For another example of how LINQ to SQL can help manage cross-table relationships for us and help clean up our code, let's look at an example below where I'm creating a new Order for an existing customer.  After setting the required ship date and freight costs for the order, I then create two order line-item objects that point to the products the customer is ordering.  I then associate the order with the customer, and update the database with all of the changes.

Figure 9

As you can see, the programming model for performing all of this work is extremely clean and object oriented. 


View Entire Article

Article Feedback

Title:  
Name:  
Url: ( Optional )
Comment:  
Please add 1 and 7 and type the answer here:

User Comments

Title: Excellent   
Name: Wayne
Date: 7/23/2008 12:27:59 AM
Comment:
Excellent article, Well done, a really good read.
Title: Thanks a lot   
Name: Andi
Date: 12/2/2007 11:25:10 AM
Comment:
Thank you for this great article!!!






Ads Powered by Lake Quincy Media
Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2008 ASPAlliance.com  |  Page Processed at 7/25/2008 3:31:35 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search