When will a DataContext open a database connection?

I use L2S to access my MSSQL 2008 Express server. I would like to know when a DataContext will open a database connection? and he will close the connection immediately after opening it?

For example:

var dc = new TestDB();  // connection opened and closed?

dc.SomeTable.InsertOnSubmit(obj);  // connection opened and closed?

foreach(var obj in dc.SomeTable.AsEnumerable())  // connection opened and closed?
{
    ...  // connection opened and closed?
}

dc.SubmitChanges();     // connection opened and closed?
+5
source share
3 answers

The connection is made when you really start the enumeration and when you click SubmitChanges (if there are changes that need to be made). I'm not sure that in the above code, only one connection is opened and used, but I know that in the two places that I mentioned, you will refer to the connection.

LinqPad dimecasts. Linq 2 Sql

, - (getTenSomethingElse (s, s, s)) db, ,

partial class MyDataContext
{
    // builds the tree to pull data from the db that matches a criteriea and pass it a ctor of another class
    public System.Linq.IQueryable<SomethingElse> getSomethingElse(string searchTerm, string searchValue, string orderBy)
    {
        var items = 
            from s in 
            this.Somethings 
            select new SomethingElse(s);

        return items.Where(searchTerm, searchValue).OrderBy(orderBy);
    }

    // calls the above method but adds take 10 to that tree
    public System.Linq.IQueryable<SomethingElse> getTenSomethingElse(string searchTerm, string searchValue, string orderBy)
    {
        var items = 
            from s in 
            this.getSomethingElse(searchTerm, searchValue, orderBy) 
            select s;

        return items.Take(10);
    }
}

IDK , , , , .

, , "Where (s, s)" ScottGu awesome blog

+2

LINQ to SQL : SubmitChanges().

, , , , .

foreach(var obj in dc.SomeTable.AsEnumerable()) - , .

+2

LINQ to SQL, , , , SubmitChanges , .

, DbConnection, DataContext. , , DataContext SubmitChanges ( , ).

0

All Articles