0
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 close the connection;

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

ashkufaraz
  • 5,179
  • 6
  • 51
  • 82

2 Answers2

1

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

Community
  • 1
  • 1
Manatherin
  • 4,169
  • 5
  • 36
  • 52
0

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.

Anton Gogolev
  • 113,561
  • 39
  • 200
  • 288