开发者

close connection database

开发者 https://www.devze.com 2023-03-26 00:38 出处:网络
DataClassesDataContext dc = new DataClassesDataContext(); private string GetPropertyCompany() { var res=from b in dc.Tbl1 select b;
DataClassesDataContext dc = new DataClassesDataContext();

private string GetPropertyCompany()
{
  var res=from b in dc.Tbl1 select b;
  string a;
  foreach(var item in res)
      a+=item.name;
  //    dc.Connection.Close();

  return a;
}

This code requires a close connection;

me should always clo开发者_运维问答se the connection;

without dc.Connection.Close(); work fine!!!!


take a look at Do I have to close the SQL Connection manually if I use Linq? in particular

LINQ to SQL will open and close connections when it needs to

Although if that code is in its own class you may wish to add a destructor that disposes of the data context, though that is up to you


I doubt that this is the actual code, but nevertheless here's why you're having a problem.

var res = from b in dc.Tbl1 select b; 

is not actually executed (that is, database isn't hit) until after you "access" res variable (i.e., 'foreach' over it), which apparently happens elsewhere. When you do access res the actual DataContext is already closed, hence the error.

0

精彩评论

暂无评论...
验证码 换一张
取 消