title: Does SqlCommand.ExecuteReader ever automatically open the db connection?
body: <p>I am noticing some odd behavior on my web page. I have a WCF Data service that serves up JSON to fill up a jqGrid. The service is called using javascript/ajax.</p>
  
  <p>Then I have some server-side code that also calls the same WCF service to get data. </p>
  
  <p>Inside my WCF Service I run cmd.ExecuteReader() without a prior open connection, and it doesn't complain about the connection in certain cases -- it seems to be when I'm calling the data service from javascript. However when I call the service from code-behind, ie server-side, I get the error that says "ExecuteReader requires an open and available connection". </p>
  
  <p>Does anyone know about this issue? Ive narrowed it down as much as possible. It appears the only difference is whether I call the service from client side or server side. Here is my code:</p>
  
  <pre><code>[ServiceContract(Namespace = "")]
  [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
  public class JsonService
  {
      static String _connection = ConfigMgr.ConnectionStrings["MyConnStr"];
      static DomainEntities dbContext = new DomainEntities(_connection);
  
      [OperationContract]
      [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest,
                           RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
      public JsonGrid Get()
      {
          return new JsonGridContract(dbContext.Products.ToJson()); 
      }
  }
  </code></pre>
  
  <p>Below is where ExecuteReader() is called. It intercepts the provider, converts the expression tree to SQL, and then executes it parsing the results to string-based JSON rather than the domain objects. </p>
  
  <pre><code>    public static List&lt;JsonRow&gt; ToJson(this IQueryable queryable)
      {
          Expression expression = queryable.Expression;
          expression = Evaluator.PartialEval(expression);
  
          if !(queryable.Provider is JsonQueryProvider)
                throw new InvalidOperationException("Provider is invalid");
  
          String table = (queryable.Provider as JsonQueryProvider).Table; 
  
          SqlConnection connection = (queryable.Provider as JsonQueryProvider).Connection; 
  
          Type elementType = TypeSystem.GetElementType(expression.Type);
  
          TranslateResult result = new QueryTranslator(table).Translate(expression);
  
          SqlCommand cmd = connection.CreateCommand();
  
          cmd.CommandText = result.CommandText;
  
          SqlDataReader reader = cmd.ExecuteReader();
  
          List&lt;JsonRow&gt; jsonResult = new List&lt;JsonRow&gt;(); 
  
          while (reader.Read())
              {
                  JsonRow instance = new JsonRow(reader.FieldCount); 
  
                  for (int i = 0, n = reader.FieldCount; i &lt; n; i++)
                  {
                      var items = instance.Items; 
  
                      if (reader.IsDBNull(i))
                      {
                          items[i] = string.Empty;  
                      }
                      else
                      {
                          items[i] = reader[i].ToString(); 
                      }
                  }
  
                  jsonResult.Add(instance); 
              }
  
          reader.Close(); 
  
          return jsonResult; 
      }
  </code></pre>
  
  <p>As noted before this method executes fine even though I never open the connection. I am using AJAX client-side, </p>
  
  <pre><code>  $.ajax(
              {
                  type: "POST",
                  contentType: "application/json; charset=utf-8",
                  url: "Services/JsonService.svc/Get",
                  data: {},
                  dataType: "json",
                  success: function (data, textStatus) {
                      if (textStatus == "success") {
                          var thegrid = $("#jqGrid")[0];
                          thegrid.addJSONData(data.d);
                      }
                  },
                  error: function (data, textStatus) {
                      alert('An error has occured retrieving data.');
                  }
              });
          }
  </code></pre>