Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
4_linq_to_sql_hands_on_lab.doc
Скачиваний:
0
Добавлен:
01.05.2025
Размер:
562.18 Кб
Скачать

Task 6 – Using Transactions

  1. In the Solution Explorer, right-click References, then click Add Reference

  2. In the .NET tab, click System.Transactions, then click OK

By default LINQ to SQL uses implicit transactions for insert/update/delete operations. When SubmitChanges() is called, it generates SQL commands for insert/update/delete and wraps them in a transaction. But it is also possible to define explicit transaction boundaries using the TransactionScope the .NET Framework 2.0 provides. In this way, multiple queries and calls to SubmitChanges() can share a single transaction. The TransactionScope type is found in the System.Transactions namespace, and operates as it does with standard ADO.NET.

  1. At the top of Program.cs, add the following using directive:

using System.Transactions;

  1. In Main, replace the existing code with the following code to have the query and the update performed in a single transaction:

static void Main(string[] args)

{

NorthwindDataContext db = new NorthwindDataContext();

using (TransactionScope ts = new TransactionScope())

{

var q =

from p in db.Products

where p.ProductID == 15

select p;

Product prod = q.First();

// Show UnitsInStock before update

Console.WriteLine("In stock before update: {0}", prod.UnitsInStock);

if (prod.UnitsInStock > 0) prod.UnitsInStock--;

db.SubmitChanges();

ts.Complete();

Console.WriteLine("Transaction successful");

}

Console.ReadLine();

}

  1. Press F5 to debug the application

Lab Summary

Instructor's Note: LINQ to SQL is still an early technology that is evolving, but sufficient progress has been made to demonstrate powerful data capabilities.

In this lab you performed the following exercises:

Exercise 1 – Creating your first LINQ to SQL application

Exercise 2 – Creating an object model from a database

Exercise 3 – Using code generation to create the object model

Exercise 4 – Modifying database data

In this lab, you learned about how the LINQ Project is advancing query capabilities in the .NET Framework. You mapped database tables to .NET classes and populated objects with live data. You also saw how seamlessly data can be retrieved and updated. Finally, you saw how richer capabilities such as transactions, custom queries, and object identity can make it easier for developers to simply concentrate on the application logic. LINQ to SQL provides a powerful bridge from objects to relational data and makes data-driven applications easier to build than ever.

Thank you for trying LINQ to SQL. We hope you enjoy using LINQ in Visual Studio 2008.