Is my database connection closed? (Linq to Sql)

I use Linq to SQL and as soon as possible I read in a blog post about closing database connections. As an example, they showed that a variable is converted to a list (using .ToList ()) instead of actually returning a Linq query. I have the code below:

 public static bool HasPassword(string userId)
 {

    ProjDataContext db = new ProjDataContext();

    bool hasPassword = (from p in db.tblSpecUser
                                    where p.UserID == userId
                                    select p.HasPassword).FirstOrDefault();


    return hasPassword;
 }

Is this query accurate? Or will the database connection remain open longer than necessary?

Thanks for any advice.

+3
source share
5 answers

. (, , , ) , DataContext. , DataContext . , , dispose , DataContext.

using (ProjDataContext db = new ProjDataContext()) {
    bool hasPassword = (from p in db.tblSpecUser
                                    where p.UserID == userId
                                    select p.HasPassword).FirstOrDefault();


    return hasPassword;
}

, db.Dispose() , .

: DataContext ( Reflector) (FW 3.5), DataContext.Dispose:

protected virtual void Dispose(bool disposing)
{
    if (disposing)
    {
        if (this.provider != null)
        {
            this.provider.Dispose();
            this.provider = null;
        }
        this.services = null;
        this.tables = null;
        this.loadOptions = null;
    }
}

, :

  • , DbConnection, (TextWriter) DbTransaction.
  • CommonDataServices.
  • .
  • LoadOptions.

, (DbConnection DbTransaction). , TextWriter , , TextWriter DataContext, . FileWriter, .

, , - - , dispose, , .

, , casparOne:

, - .

, , .

+5

, , . , DataContext.

DataContext IDisposable, Dispose DataContext , .

, , Dispose DataContext .

, . , . DataContext IDisposable, , , , .

, LINQ, LINQ-to-Entities, Dispose, , ObjectContext ( IDisposable) , Dispose .

, , . DataContext, . ObjectTrackingEnabled false, DataContext , . ( ) , , DataContext, .

, (,

+2

Linq-To-SQL , , (db ). , , - SQL , Linq.

L2S , , , . .

0

using. , .

public static bool HasPassword(string userId)
 {

    using(var db = new ProjDataContext())
    {

       bool hasPassword = (from p in db.tblSpecUser
                                    where p.UserID == userId
                                    select p.HasPassword).FirstOrDefault();


        return hasPassword;
    }
}
0

, db () . ( ) .

0

Source: https://habr.com/ru/post/1734789/


All Articles