LINQ to SQL Code Examples
Once we've modeled our database using the LINQ to SQL designer, we can then easily write code to work against it. Below are a few code examples that show off common data tasks:
1) Query Products From the Database
The code below uses LINQ query syntax to retrieve an IEnumerable sequence of Product objects. Note how the code is querying across the Product/Category relationship to only retrieve those products in the "Beverages" category:
C#:
VB:
2) Update a Product in the Database
The code below demonstrates how to retrieve a single product from the database, update its price, and then save the changes back to the database:
C#:
VB:
Note: VB in "Orcas" Beta1 doesn't support Lambdas yet. It will, though, in Beta2 - at which point the above query can be rewritten to be more concise.
3) Insert a New Category and Two New Products into the Database
The code below demonstrates how to create a new category, and then create two new products and associate them with the category. All three are then saved into the database.
Note below how I don't need to manually manage the primary key/foreign key relationships. Instead, just by adding the Product objects into the category's "Products" collection, and then by adding the Category object into the DataContext's "Categories" collection, LINQ to SQL will know to automatically persist the appropriate PK/FK relationships for me.
C#
VB:
4) Delete Products from the Database
The code below demonstrates how to delete all Toy products from the database:
C#:
VB:
5) Call a Stored Procedure
The code below demonstrates how to retrieve Product entities not using LINQ query syntax, but rather by calling the "GetProductsByCategory" stored procedure we added to our data model above. Note that once I retrieve the Product results, I can update/delete them and then call db.SubmitChanges() to persist the modifications back to the database.
C#:
VB:
6) Retrieve Products with Server Side Paging
The code below demonstrates how to implement efficient server-side database paging as part of a LINQ query. By using the Skip() and Take() operators below, we'll only return 10 rows from the database - starting with row 200.
C#:
VB:
Summary
LINQ to SQL provides a nice, clean way to model the data layer of your application. Once you've defined your data model you can easily and efficiently perform queries, inserts, updates and deletes against it.
Hopefully the above introduction and code samples have helped whet your appetite to learn more. Over the next few weeks I'll be continuing this series to explore LINQ to SQL in more detail.
Hope this helps,
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment