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:
Use the exclaim.aspx page you created in the preceding section, "Updating Data with a LINQ Query."
In Design view, add a Button control with the text Insert and double-click the button to create a handler for the Click event.
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()
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.
Read now
Unlock full access