2009-09-16 55 views
5

我使用L2S访问我的MSSQL 2008 Express服务器。我想知道DataContext什么时候会打开到DB的连接?并在打开它后立即关闭连接?DataContext何时会打开到数据库的连接?

例如:

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? 
+0

不是L2S专业版,但我希望它只能在SubmitChanges()中打开和关闭。 – mxmissile 2009-09-16 16:31:46

回答

2

建立连接,当你打的SubmitChanges(如果有要进行更改)。我不知道,如果在上面的代码中只有一个连接被打开和使用,但我知道在我提到的两个地方,你会调用连接。

您需要开始查看LinqPadhow to use it而不是dimecasts。还检查了他们的一系列关于Delayed Execution features of 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); 
    } 
} 

IDK你,但我认为这是相当真棒考虑正在完成所有的工作,多数民众赞成。

哦顺便说一句,对“在哪里(S,S)”扩展的更多信息可以在ScottGu's awesome blog

+0

您提出了一个关于'System.Linq.IQueryable'函数的非常好的观点。谢谢,这有帮助。 – 2009-11-18 05:36:19

0

不知道LINQ to SQL的内部,但常识告诉数据库连接必须打开的时间尽可能少,因此可以合理预期的SubmitChanges将打开连接,完成它的工作,然后关闭连接。

注意无论如何,你可以有机会获得由DataContext的使用的DbConnection对象。也许如果你打开手动连接,在DataContext将不后的SubmitChanges完成关闭它(只是猜测,从来没有尝试过)。当你真正开始列举和

2

LINQ发现SQL是很好的你:它会打开和关闭的SubmitChanges数据库连接()。

另外,如果您插入多个记录,插入将包含在单个事务中,因此它们全部成功或者全部失败。

foreach(var obj in dc.SomeTable.AsEnumerable())的情况下,数据库连接打开和关闭 - 只有一次,在此期间检索所有记录。

相关问题