Chapter 7: Working with Data

211

VB:

Function InsertCustomer() As Integer

Dim cust = New Customer With

{

.Name = "Jim"

}

Dim myShop As New MyShopDataContext

myShop.Customers.InsertOnSubmit(cust)

myShop.SubmitChanges()

Return cust.CustomerID

End Function

As shown here, each collection property, such as Customers, has an InsertOnSubmit method that takes an object of the collection’s type, Customer in this case. Don’t forget to call SubmitChanges, or else you won’t see any changes to your data. The next section discusses updates. Once the insert executes, with SubmitChanges, the new object, cust, will be updated with the new CustomerID, which you read and return to calling code.

Updating Data with LINQ to SQL

To update data, you need to get an object for the record you want to update, change the object you received, and then save the changes back to the database. The following example shows how to update a record:

C#:

private static void UpdateCustomer(int custID)

{

var myShop = new MyShopDataContext();

var customers =

from cust in myShop.Customers where cust.CustomerID == custID select cust;

Customer firstCust = customers.SingleOrDefault();

if (firstCust != null)

{

firstCust.Name = "James";

}

myShop.SubmitChanges();

}

Page 234
Image 234
Microsoft 9GD00001 manual Updating Data with Linq to SQL, 211