现在遇到一个问题,我有一部分代码是用ADO.NET写的,我想加入Linq To SQL怎么办?
看下面代码:
 1 string connString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=c:\northwind.mdf;
 2     Integrated Security=True; Connect Timeout=30; User Instance=True";
 3 SqlConnection nwindConn = new SqlConnection(connString);//创建一个链接对象
 4 nwindConn.Open();
 5 
 6 Northwnd interop_db = new Northwnd(nwindConn);//创建DataContext对象
 7 
 8 SqlTransaction nwindTxn = nwindConn.BeginTransaction();//创建一个事务
 9 
10 try
11 {
12     SqlCommand cmd = new SqlCommand(
13         "UPDATE Products SET QuantityPerUnit = 'single item' WHERE ProductID = 3");
14     cmd.Connection = nwindConn;
15     cmd.Transaction = nwindTxn;
16     cmd.ExecuteNonQuery();//使用ADO.NET执行更新操作
17 
18     interop_db.Transaction = nwindTxn;//给DataContext添加一个事务
19 
20     Product prod1 = interop_db.Products
21         .First(p => p.ProductID == 4);
22     Product prod2 = interop_db.Products
23         .First(p => p.ProductID == 5);
24     prod1.UnitsInStock -= 3;
25     prod2.UnitsInStock -= 5;
26 
27     interop_db.SubmitChanges();//执行操作
28 
29     nwindTxn.Commit();//提交事务
30 }
31 catch (Exception e)
32 {
33     Console.WriteLine(e.Message);
34     Console.WriteLine("Error submitting changesLinq TO SQL中ADO.NET与Linq的整合使用_字符串 all changes rolled back.");
35 }
36 
37 nwindConn.Close();
Northwnd 是一个DataContext对象,好比我们创建Linq中的xxxxDataContext对象一样.
看到代码是不是感觉整合起来是那么的简单?
那么为什么两个东西可以整合到一起呢?因为 LINQ To SQL 是 ADO.NET 系列技术的一部分,是基于由 ADO.NET 提供的服务,您就可以重复使用 ADO.NET 命令和一个 DataContext 之间的连接.

再给一个非常直观的方法.在Linq中执行一条SQL语句使用以下代码:
1 DataContext.ExecuteCommand("UPDATE Products SET UnitPrice = UnitPrice + 1.00");
很熟悉吧.是不是有点像企业库的SQL操作?
大家应该都知道Linq To SQL是生成了一连串的SQL字符串,最后执行操作的,实际上是对ADO.NET的一个封装而已.