原因一:沒有打開MSDTC服務
步驟:
- Componet Services-->右擊My Computer--->Start MSDTC
- Componet Services-->右擊My Computer-->屬性--->MSDTC-->安全配置--->勾選上我紅線標註的部分。
原因二: 防火牆阻止
解決方法,添加135端口到Exception
原因三:使用了多個連接
1: using (TransactionScope ts = new TransactionScope())
2: {
3: //...
4: ts.complete();
5: }
TransactionScope不允許一個事務裏有多個連接,解決辦法是我們加個基礎類,讓所有的都是用同一個連接
1: public class BaseDataAccess
2: {
3: private SqlConnection mSqlconnection;
4: protected SqlConnection sqlConnection
5: {
6: get
7: {
8: if (mSqlconnection == null) mSqlconnection = new SqlConnection(SqlHelper.mConnectionString);
9: return mSqlconnection;
10: }
11: }
12: }
ADO.NET 2.的一個新特徵多數據結果集(Multiple Active Result Sets,簡稱MARS)-它允許在單個連接上執行多重的數據庫查詢或存儲過程。這樣的結果是,你能夠在單個連接上得到和管理多個、僅向前引用的、只讀的結果集。目前實現這個功能的數據庫只有Sql Server 2005。所以當我們針對Sql Sever 2005的時候,需要重新審視DataReader對象的使用。使用SqlServer 2005,可以在一個Command對象上同時打開多個DataReader,節約數據庫聯接所耗費的服務器資源,在實際開發中普遍存在的一種典型的從數據庫中讀寫數據的情形是,你可以使用多重連接而現在只用一個連接就足夠了。例如,如果你有一些來自於幾個表中的數據-它們不能被聯結到一個查詢中,那麼你就會有多重的連接-每個連接都有一個與之相關連的命令用於讀取數據。同樣,如果你正在向一個表寫數據,那麼你需要另外一個連接或連接集合-如果有多個表要被更新的話。
例如下面的代碼
1: //MultipleActiveResultSets=true打開聯接
2: string connstr = "server=(local);database=northwind;integrated security=true;MultipleActiveResultSets=true";
3: SqlConnection conn = new SqlConnection(connstr);
4: conn.Open();
5: SqlCommand cmd1 = new SqlCommand("select * from customers", conn);
6: SqlCommand cmd2 = new SqlCommand("select * from orders", conn);
7: SqlDataReader rdr1 = cmd1.ExecuteReader();
8: // next statement causes an error prior to SQL Server 2005
9: SqlDataReader rdr2 = cmd2.ExecuteReader();
10: // now you can reader from rdr1 and rdr2 at the same time.
11: conn.Close();
王德水 祝你編程愉快