Microsoft 9GD00001 Computer Accessories User Manual


 
210 Microsoft Visual Studio 2010: A Beginner’s Guide
VB:
Dim myShop As New MyShopDataContext
Dim customers As IEnumerable =
myShop.GetCustomers()
For Each custOrd In customers
Console.WriteLine("Name: " & custOrd.Name)
Next
And here’s the output:
Name: Meg
Name: Joe
Name: May
Just call myShop.GetCustomers and you’ll receive a collection of Customer objects.
There are many more advanced scenarios that you can handle with LINQ, but this
is just a beginner’s guide. However, you now have a solid base of query techniques that
will get you started. In addition to querying a database, you’ll need to perform insert
operations, which is next.
TIP
LINQ to SQL generates SQL (Structured Query Language) statements to send to the
database for your queries. If you would like to see the generated SQL, set a breakpoint
on the line after the query and run the program with debugging. When you hit the
breakpoint, hover over the variable holding query results and you’ll see the SQL
statement.
Inserting Data with LINQ to SQL
To insert a new record into a table, you’ll need to create an instance of the LINQ to SQL
class for that table, call a method to insert, and then call another method to commit the
changes. The following example shows how to add a new record to the Customer table:
C#:
private static int InsertCustomer()
{
var cust = new Customer { Name = "Jim" };
var myShop = new MyShopDataContext();
myShop.Customers.InsertOnSubmit(cust);
myShop.SubmitChanges();
return cust.CustomerID;
}