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:
When we call "SubmitChanges()" above
a new row will be created in our products table.
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
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.