1

EF5 是否有可能在使用 DBContext 时不会立即关闭连接

 public void UpdateCategory(Models.Category catData)
    {
        if (catData == null) return;
        using (var cntx = new DataContext())
        {
            //IN THE LINE BELOW A CONNECTION IS DEFINITELY OPENED BUT IS IT IMMEDIATELY CLOSE????
            var cat = cntx.Set<Category>().FirstOrDefault(c => c.CategoryId == catData.CategoryId);

            if (cat == null) return;

            if (!cat.LastChanged.Matches(catData.LastChanged))
                throw new ConcurrencyException(cat.GetType().ToString());

            cat.CategoryName = catData.CategoryName;

            cntx.DbContext.Entry<Category>(cat).State = System.Data.EntityState.Modified;

            //AFTER THE NEXT LINE DO I HAVE 2 CONNECTIONS OPENED? OR WAS THE CONNECTION OPENED FROM THE FIRST QUERY CLOSED ALREADY?
            cntx.SaveChanges();


            catData.LastChanged = cat.LastChanged;
        }

    }

是否存在相同上下文创建\打开 2 个连接而留下一个打开的场景\错误?

4

1 回答 1

1

如果您在这里查看 MSDN:http: //msdn.microsoft.com/library/vstudio/bb896325

实体框架仅在需要时打开连接,例如执行查询或调用 SaveChanges,然后在操作完成时关闭连接。

调用查询方法时,连接会打开,并保持打开状态,直到 ObjectResult 被完全消耗或释放。

public void UpdateCategory(Models.Category catData)
{
    if (catData == null) return;
    using (var cntx = new DataContext())
    {
        //IN THE LINE BELOW A CONNECTION IS DEFINITELY OPENED BUT IS IT 
        //IMMEDIATELY CLOSE? => YES!
        var cat = cntx.Set<Category>()
                          .FirstOrDefault(c => c.CategoryId == catData.CategoryId);

        if (cat == null) return;

        if (!cat.LastChanged.Matches(catData.LastChanged))
            throw new ConcurrencyException(cat.GetType().ToString());

        cat.CategoryName = catData.CategoryName;

        cntx.DbContext.Entry<Category>(cat).State = System.Data.EntityState.Modified;

        //AFTER THE NEXT LINE DO I HAVE 2 CONNECTIONS OPENED? => NO
        cntx.SaveChanges();


        catData.LastChanged = cat.LastChanged;
    }

}

是否存在相同的上下文创建\打开 2 个连接而留下一个打开的场景?

是的,当使用带有 DbContext 的事务时,它将打开第二个连接,请看这里:http ://www.digitallycreated.net/Blog/48/entity-framework-transactionscope-and-msdtc

于 2013-08-19T20:31:19.727 回答