.net SqlConnection not being closed even when within a using { }

后端 未结 6 1298

Please help!

Background info

I have a WPF application which accesses a SQL Server 2005 database. The database is running locally on the machine the appl

6条回答
  •  你的背包
    2021-02-13 02:10

    The SqlProvider used by the LINQ DataContext only closes the SQL connection (through SqlConnectionManager.DisposeConnection) if it was the one to open it. If you give an already-open SqlConnection object to the DataContext constructor, it will not close it for you. Thus, you should write:

    using (SqlConnection conn = GetConnection())
    using (DataContext db = new DataContext(conn))
    {
        ... Code 
    }
    

提交回复
热议问题