DataContext何时打开与DB的连接?

时间:2009-09-16 16:23:02

标签: linq-to-sql sql-server-2008 .net-3.5

我正在使用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?

3 个答案:

答案 0 :(得分:3)

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

您需要开始在LinqPad处查看how to use itdimecasts。另请查看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关于你,但我认为考虑到所有正在进行的工作,这是相当棒的。

哦,顺便说一句,有关“Where(s,s)”扩展名的更多信息可以在ScottGu's awesome blog上找到

答案 1 :(得分:2)

LINQ to SQL对您有好处:它将在SubmitChanges()中打开和关闭数据库连接。

此外,如果您插入多条记录,插入内容将包含在单个事务中,因此它们都会成功或者都会失败。

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

答案 2 :(得分:0)

不了解LINQ to SQL内部,但常识告诉必须以尽可能少的时间打开数据库连接,因此可以合理地期望SubmitChanges打开连接,它的工作原理,然后关闭连接。

请注意,您可以访问DataContext使用的DbConnection对象。也许如果您手动打开连接,DataContext将不会在SubmitChanges完成后关闭它(只是猜测,从未尝试过)。

相关问题