DataContext何时打开与DB的连接?

Era*_*lel 6 .net-3.5 sql-server-2008 linq-to-sql

我正在使用L2S访问我的MSSQL 2008 Express服务器.我想知道DataContext何时会打开与DB的连接?它打开后会立即关闭连接吗?

例如:

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?
Run Code Online (Sandbox Code Playgroud)

All*_*ice 3

当您实际开始枚举并点击 SubmitChanges(如果需要进行更改)时,就会建立连接。我不确定在上面的代码中是否仅打开和使用一个连接,但我知道在我提到的那两个地方,您将调用一个连接。

您需要开始研究LinqPad以及如何在dimecasts上使用它。另请查看他们关于Linq 2 Sql 的延迟执行功能的系列

请注意,类似这样的 (getTenSomethingElse(s,s,s)) 不会查询数据库,至少在您开始枚举返回值之前不会

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

我不知道你的情况,但考虑到正在完成的所有工作,我认为这相当棒。

哦,顺便说一句,有关“Where(s,s)”扩展的更多信息可以在ScottGu 的精彩博客上找到