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

Insert and Delete Examples

In addition to updating existing rows in the database, LINQ to SQL obviously also enables you to insert and delete data.  You can accomplish this by adding/removing data objects from the DataContext's table collections, and by then calling the SubmitChanges() method.  LINQ to SQL will keep track of these additions/removals, and automatically execute the appropriate SQL INSERT or DELETE statements when SubmitChanges() is invoked.

Inserting a New Product

I can add a new product to my database by creating a new "Product" class instance, setting its properties, and then by adding it to my DataContext's "Products" collection:

Figure 6

When we call "SubmitChanges()" above a new row will be created in our products table.

Deleting Products

Just as I can express that I want to add a new Product to the database by adding a Product object into the DataContext's Products collection, I can likewise express that I want to delete a product from a database by removing it from the DataContext's Products collection:

Figure 7

Note above how I'm retrieving a sequence of discontinued products that no one has ever ordered using a LINQ query, and then passing it to the RemoveAll() method on my DataContext's "Products" collection.  When we call "SubmitChanges()" above all of these Product rows will be deleted from our products table.


View Entire Article

Article Feedback

Title:  
Name:  
Url: ( Optional )
Comment:  
Please add 8 and 3 and type the answer here:

User Comments

Title: Linq doesn't update   
Name: Moez Tounsi
Date: 10/7/2008 12:15:53 PM
Comment:
Following the example above, ling will add a new record with the new parameters.
We have to handle the deletion of the old element.
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!!!






Community Advice: ASP | SQL | XML | Regular Expressions | Windows


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