c# - Does Linq to Sql close connections automatically? -


this question has answer here:

does linq sql close connections automatically? or should use using?

var db = new datacontext(); // codes 

or

using (var db = new datacontext()) {     // codes } 

when using using statement connection managed automatically.the datacontext class implements idisposable interface, need call dispose on datacontext implementation whenever finished it.

from c# in depth

there few reasons implemented idisposable:

  • if application logic needs hold onto entity beyond when datacontext expected used or valid can enforce that
    contract calling dispose. deferred loaders in entity will
    still referencing datacontext , try use if any
    code attempts navigate deferred properties. these attempts
    fail. dispose forces datacontext dump cache of
    materialized entities single cached entity not
    accidentally keep alive entities materialized through that
    datacontext, otherwise cause appears memory
    leak.
  • the logic automatically closes datacontext connection can tricked leaving connection open. datacontext relies on application code enumerating results of query since getting end of resultset triggers connection close. if application uses ienumerable's movenext method instead of foreach statement in c# or vb, can exit enumeration prematurely. if application experiences problems connections not closing , suspect automatic closing behavior not working can use dispose pattern work around.

Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -