Skip to Content
ASP.NET 3.5 For Dummies®
book

ASP.NET 3.5 For Dummies®

by Ken Cox
February 2008
Intermediate to advanced
428 pages
8h 52m
English
For Dummies
Content preview from ASP.NET 3.5 For Dummies®

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

ASP.NET 3.5 Unleashed

ASP.NET 3.5 Unleashed

Stephen Walther
ASP.NET 4 Unleashed

ASP.NET 4 Unleashed

Stephen Walther, Kevin Hoffman, Nate Dudek

Publisher Resources

ISBN: 9780470195925Purchase book