使用DBContext(如
)时,EF5是否可能不会立即关闭连接 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;
}
}
是否有相同的上下文创建的scenerios \ bugs \打开2个连接,一个打开?
答案 0 :(得分: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