2010-11-26 108 views
2

我正在用c#構建應用程序,並決定使用DAL(SQL Server)的企業庫。企業庫管理連接

我不記得在哪裏,但我讀過一篇關於EntLib的文章,它說自動關閉連接。

這是真的嗎?

如果不是,管理中間層連接的最佳方法是什麼? 在每種方法中打開和關閉?

以上是我如何使用EntLib

public DataSet ReturnSomething 
{ 
    var sqlStr = "select something"; 
    DbCommand cmd = db.GetSqlStringCommand(sqlStr); 
    db.AddInParameter(cmd, "@param1", SqlDbType.BigInt, hotelID); 
    db.AddInParameter(cmd, "@param2", SqlDbType.NVarChar, date); 
    return db.ExecuteDataSet(cmd); 

}

預先感謝的樣品的方法。

回答

2

ExecuteDataSet方法返回一個包含所有數據的DataSet對象。這給你你自己的本地副本。到ExecuteDataSet調用打開一個連接,填充DataSet中,並返回結果

以獲得更多信息之前關閉連接:

http://msdn.microsoft.com/en-us/library/ff648933.aspx

+0

如果我想要一個DataReader或插入,刪除,更新呢?連接將如何處理? – StrouMfios 2010-11-26 15:22:40

0

我想你應該有這樣的事情作爲一個靜態類將爲您的圖書館子系統提供正確連接的外觀。

public static class SystemFacade { 
    // Used as a subsystem to which the connections are provided. 
    private static readonly SystemFactory _systemFactory = new SystemFactory(); 

    public static IList<Customer> GetCustomers() { 
     using (var connection = OpenConnection(nameOfEntLibNamedConnection)) 
      return _systemFactory.GetCustomers(connection); 
    } 

    public static DbConnection OpenConnection(string connectionName) { 
     var connection = 
      // Read EntLib config and create a new connection here, and assure 
      // it is opened before you return it. 

     if (connection.State == ConnectionState.Closed) 
      connection.Open(); 

     return connection;    
    } 
} 

internal class SystemFactory { 
    internal IList<Customer> GetCustomers(DbConnection connection) { 
     // Place code to get customers here. 
    } 
} 

並使用此代碼:

public class MyPageClass { 
    private void DisplayCustomers() { 
     GridView.DataSource = SystemFacade.GetCustomers(); 
    } 
} 

在此代碼示例,你有一個靜態類,它提供了一個類庫的功能和特性。 Façade類用於爲用戶提供所有可能的操作,但不希望讓用戶感到頭疼,等等。所需的只是基礎數據存儲區外的客戶列表。然後,撥打GetCustomers就可以了。

Facade是一個「智能」類,它知道從哪裏獲取信息,因此創建相應的連接並從子系統工廠訂購客戶。工廠按照要求提供服務,接通可用的連接並找回客戶,而無需再提出任何問題。

這有幫助嗎?

+0

所以我讀過的文章是錯誤的,我必須關閉並打開每個用途的連接!感謝您的幫助Will Marcouiller – StrouMfios 2010-11-26 15:32:20

+0

不,您不需要手動管理連接 - 該塊會自動打開並關閉連接。這個解決方案是過度殺毒,特別是如果你使用數據集。 – 2010-11-29 18:35:25

0

是的,EntLib關閉你的連接(實際上它將它們釋放回連接池)。這是我們最初開始使用EntLib的主要原因。

但是,對於所有新的開發,我們現在繼續使用實體框架,我們發現效率更高。