locked
Should I close connection in Entity framework RRS feed

  • Question

  • User1916581254 posted

    Good Day!

    Recently switched to entity
    Should I close the connection using the Dispose method?

    Friday, February 26, 2016 2:23 PM

Answers

  • User281315223 posted

    If you are using connections, its generally preferred to take advantage of the using keyword, which will properly scope your connection and handle any closing / disposal for you :

    using(var context = new YourDataContext())
    {
         // Use it here
    }
    
    // At this point, the connection has been closed and disposed of

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, February 26, 2016 2:50 PM
  • User-698989805 posted

    Hello starter88! Linq uses DataContext for database connections and it is being handled with the 'using' keyword. For more, you could refer to the following link:

    http://stackoverflow.com/questions/23950359/linq-to-entities-objectcontext-and-db-connections

     

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, February 26, 2016 5:17 PM

All replies

  • User281315223 posted

    If you are using connections, its generally preferred to take advantage of the using keyword, which will properly scope your connection and handle any closing / disposal for you :

    using(var context = new YourDataContext())
    {
         // Use it here
    }
    
    // At this point, the connection has been closed and disposed of

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, February 26, 2016 2:50 PM
  • User-698989805 posted

    Hello starter88! Linq uses DataContext for database connections and it is being handled with the 'using' keyword. For more, you could refer to the following link:

    http://stackoverflow.com/questions/23950359/linq-to-entities-objectcontext-and-db-connections

     

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, February 26, 2016 5:17 PM
  • User36583972 posted

    Hi starter88,

    As Rion Williams  said, you can use the using keyword. It is Automatically releases the connection after performing.

    The following tutorial describes the behavior of the Entity Framework with regard to passing connections in the context and the functionality of the Database.Connection.Open() API:

    https://msdn.microsoft.com/en-us/data/dn456849.aspx

    Best Regards,

    Yohann Lu

    Monday, February 29, 2016 8:58 AM