8.6. Inserting Data with the DataContext

You don't use LINQ to SQL to insert data because you're not acting on a set of data. Instead, you use the DataContext classes that you create earlier in the section, "Creating the database access code." Take a look at the code in Step 3; the key is the DataContext object's InsertOnSubmit() method that acts like Add() in most collections. Follow these steps to create a new Product object, configure it, and add it to the database:

  1. Use the exclaim.aspx page you created in the preceding section, "Updating Data with a LINQ Query."

  2. In Design view, add a Button control with the text Insert and double-click the button to create a handler for the Click event.

  3. In Source view, add the following code to the handler subroutine:

    Dim dc As New NWDataClassesDataContext
    Dim prdcts = dc.Products
    Dim prod = New Product
    prod.ProductName = "CoolJuice"
    prod.QuantityPerUnit = "8 per box"
    prod.UnitPrice = 5
    prod.SupplierID = 2
    prod.CategoryID = 1
    prod.UnitsInStock = 5
    prod.ReorderLevel = 1
    prdcts.InsertOnSubmit(prod)
    dc.SubmitChanges()
    BindData()
  4. At runtime, click the Insert button that you add in Step 2.

    The preceding code adds CoolJuice as the last item in the list of products.

NOTE

The code in Step 3 creates a DataContext object that represents the database tables and uses the variable prdcts to hold a reference to the Products collection. The variable prod represents a Product object, created from a class generated by the object relational designer.

With the ...

Get ASP.NET 3.5 For Dummies® now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.