title: EntityFramework Exception : New transaction is not allowed because there are other threads running in the session
body: <p>I am using ServiceBrokerClass which i got from <a href="http://www.codeproject.com/KB/database/autorefresh_ef_ssb.aspx" rel="nofollow">CodeProject</a>. But now when i try to save any record into database using EnityFramework and .Net WPF. I am getting the following error.</p>
  
  <p>ServiceBrokerUtility Class :</p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Text;
  using System.Data.Objects;
  using System.Collections;
  using System.Data.SqlClient;
  using System.Runtime.Remoting.Messaging;
  using System.Collections.Specialized;
  
  namespace JIMS.UtilityClasses
  {
      // see http://www.codeproject.com/KB/database/autorefresh_ef_ssb.aspx
      public static class ServiceBrokerUtility
      {
          private static readonly List&lt;string&gt; connectionStrings = new List&lt;string&gt;();
          private const string sqlDependencyCookie = "MS.SqlDependencyCookie";
          private static ObjectContext objectContext;
          private static RefreshMode refreshMode;
          private static readonly Dictionary&lt;string, IEnumerable&gt; collections = new Dictionary&lt;string, IEnumerable&gt;();        
  
          static public void AutoRefresh(this ObjectContext objectContext, RefreshMode refreshMode, IEnumerable collection)
          {                        
              string efConnStr=System.Configuration.ConfigurationManager.ConnectionStrings[objectContext.Connection.ConnectionString.Replace("name=", "").Trim()].ConnectionString;
              string dbConnectionString = new System.Data.EntityClient.EntityConnectionStringBuilder(efConnStr).ProviderConnectionString;
              if (!connectionStrings.Contains(dbConnectionString))
              {
                  connectionStrings.Add(dbConnectionString);
                  SqlDependency.Start(dbConnectionString);
              }
              ServiceBrokerUtility.objectContext = objectContext;
              ServiceBrokerUtility.refreshMode = refreshMode;
              AutoRefresh(collection);
          }
  
          /// &lt;summary&gt;
          /// Stops the auto refresh.
          /// &lt;/summary&gt;
          /// &lt;param name="collection"&gt;The collection.&lt;/param&gt;
          static public void StopAutoRefresh(IEnumerable collection)
          {
              var kvp = collections.FirstOrDefault(x =&gt; x.Value == collection);
              if (!kvp.Equals(new KeyValuePair&lt;string, IEnumerable&gt;()))
                  collections.Remove(kvp.Key);
          }
  
          static private void AutoRefresh(IEnumerable collection)
          {
              var oldCookie = CallContext.GetData(sqlDependencyCookie);
              try
              {
                  var dependency = new SqlDependency();
                  collections.Add(dependency.Id, collection);
                  CallContext.SetData(sqlDependencyCookie, dependency.Id);
                  dependency.OnChange += dependency_OnChange;
                  objectContext.Refresh(refreshMode, collection);
              }
              finally
              {
                  CallContext.SetData(sqlDependencyCookie, oldCookie);
              }
          }
  
          static void dependency_OnChange(object sender, SqlNotificationEventArgs e)
          {
              if (e.Info == SqlNotificationInfo.Invalid)
              {                
                  return;
              }
              try
              {
                  var id = ((SqlDependency)sender).Id;
                  IEnumerable collection;
                  if (collections.TryGetValue(id, out collection))
                  {
                      collections.Remove(id);
                      AutoRefresh(collection);
                      var notifyRefresh = collection as INotifyRefresh;
                      if (notifyRefresh != null)
                          System.Windows.Application.Current.Dispatcher.BeginInvoke(
                           (Action)(notifyRefresh.OnRefresh));
                  }
              }
              catch (Exception ex)
              {
                  System.Diagnostics.Debug.Print("Error in OnChange: {0}", ex.Message);
              }
          }
      }
      public interface INotifyRefresh : INotifyCollectionChanged
      {
          void OnRefresh();
      }
  }
  </code></pre>
  
  <p>AutoRefreshCollection Class :</p>
  
  <pre><code>namespace JIMS.UtilityClasses
  {
      public class AutoRefreshCollection&lt;T&gt; : IEnumerable&lt;T&gt;, INotifyRefresh
          where T : EntityObject
      {
          public IEnumerable&lt;T&gt; objectQuery;
          public AutoRefreshCollection(ObjectQuery&lt;T&gt; objectQuery, RefreshMode refreshMode)
          {
              this.objectQuery = objectQuery;
              objectQuery.Context.AutoRefresh(refreshMode, this);
          }
  
          public void StopAutoRefresh()
          {
              ServiceBrokerUtility.StopAutoRefresh(this);
          }
  
          public IEnumerator&lt;T&gt; GetEnumerator()
          {
              return objectQuery.GetEnumerator();
          }
  
          IEnumerator IEnumerable.GetEnumerator()
          {
              return this.GetEnumerator();
          }
  
          public void OnRefresh()
          {
              try
              {
                  if (this.CollectionChanged != null)
                      CollectionChanged(this,
                        new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
  
              }
              catch (Exception ex)
              {
                  System.Diagnostics.Debug.Print("Error in OnRefresh: {0}", ex.Message);
              }
          }
  
          public event NotifyCollectionChangedEventHandler CollectionChanged;
      }
  }
  </code></pre>
  
  <p>My Code :</p>
  
  <pre><code>public void Create()
  {
      try
      {
          dbContext.AddToLedgers(
              new JIMSDAL.Ledger
              {
                  LedgerName = LedgerName,
                  Group = LedgerGroup,
                  Street = Street,
                  City = City,
                  PinCode = PinCode,
                  State = State,
                  Phone = Phone,
                  TIN = TIN,
                  Balance = Balance
              }
          );                
          dbContext.SaveChanges();
          JIMSMessage.Show("Ledger Created Successfully.");
          Clear();
      }
  }
  </code></pre>
  
  <p>Can anyone help me on this.</p>
  
  <p>Inner Exception Stack Trace :</p>
  
  <pre><code> at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)
     at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
     at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning()
     at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
     at System.Data.SqlClient.TdsParser.TdsExecuteTransactionManagerRequest(Byte[] buffer, TransactionManagerRequestType request, String transactionName, TransactionManagerIsolationLevel isoLevel, Int32 timeout, SqlInternalTransaction transaction, TdsParserStateObject stateObj, Boolean isDelegateControlRequest)
     at System.Data.SqlClient.SqlInternalConnectionTds.ExecuteTransactionYukon(TransactionRequest transactionRequest, String transactionName, IsolationLevel iso, SqlInternalTransaction internalTransaction, Boolean isDelegateControlRequest)
     at System.Data.SqlClient.SqlInternalConnectionTds.ExecuteTransaction(TransactionRequest transactionRequest, String name, IsolationLevel iso, SqlInternalTransaction internalTransaction, Boolean isDelegateControlRequest)
     at System.Data.SqlClient.SqlInternalConnection.BeginSqlTransaction(IsolationLevel iso, String transactionName)
     at System.Data.SqlClient.SqlInternalConnection.BeginTransaction(IsolationLevel iso)
     at System.Data.SqlClient.SqlConnection.BeginDbTransaction(IsolationLevel isolationLevel)
     at System.Data.Common.DbConnection.BeginTransaction(IsolationLevel isolationLevel)
     at System.Data.EntityClient.EntityConnection.BeginDbTransaction(IsolationLevel isolationLevel)
  </code></pre>