Do I have to close the SQL Connection manually if I use Linq?

前端 未结 3 573
我在风中等你
我在风中等你 2020-12-06 07:15

Traditionally, when we use SQL string to done some work, we have to close the sql connection before the page being closed, I was wondering if I use Linq to do the data opera

3条回答
  •  误落风尘
    2020-12-06 07:44

    I answered in detail a question about closing connections that you might find interesting here.


    Microsoft has answered this question here:

    Q. How long does my database connection remain open?

    A. A connection typically remains open until you consume the query results. If you expect to take time to process all the results and are not opposed to caching the results, apply ToList<(Of <(TSource>)>) to the query. In common scenarios where each object is processed only one time, the streaming model is superior in both DataReader and LINQ to SQL.

    The exact details of connection usage depend on the following:

    Connection status if the DataContext is constructed with a connection object.

    Connection string settings (for example, enabling Multiple Active Result Sets (MARS). For more information, see Multiple Active Result Sets (MARS).


    More detail can be found here:

    You can supply an existing ADO.NET connection when you create a LINQ to SQL DataContext. All operations against the DataContext (including queries) use this provided connection. If the connection is already open, LINQ to SQL leaves it as is when you are finished with it.

提交回复
热议问题