EntityFramework Exception : New transaction is not allowed because there are other threads running in the session

c# entity-framework exception sql-server wpf

Question

CodeProject gave me the ServiceBrokerClass, which I am using. However, I'm currently trying to use EnityFramework and.Net WPF to store any entry into a database. The following error is appearing for me.

Class: ServiceBrokerUtility

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<string> connectionStrings = new List<string>();
        private const string sqlDependencyCookie = "MS.SqlDependencyCookie";
        private static ObjectContext objectContext;
        private static RefreshMode refreshMode;
        private static readonly Dictionary<string, IEnumerable> collections = new Dictionary<string, IEnumerable>();        

        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);
        }

        /// <summary>
        /// Stops the auto refresh.
        /// </summary>
        /// <param name="collection">The collection.</param>
        static public void StopAutoRefresh(IEnumerable collection)
        {
            var kvp = collections.FirstOrDefault(x => x.Value == collection);
            if (!kvp.Equals(new KeyValuePair<string, IEnumerable>()))
                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();
    }
}

Class: AutoRefreshCollection

namespace JIMS.UtilityClasses
{
    public class AutoRefreshCollection<T> : IEnumerable<T>, INotifyRefresh
        where T : EntityObject
    {
        public IEnumerable<T> objectQuery;
        public AutoRefreshCollection(ObjectQuery<T> objectQuery, RefreshMode refreshMode)
        {
            this.objectQuery = objectQuery;
            objectQuery.Context.AutoRefresh(refreshMode, this);
        }

        public void StopAutoRefresh()
        {
            ServiceBrokerUtility.StopAutoRefresh(this);
        }

        public IEnumerator<T> 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;
    }
}

I'm 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();
    }
}

Can somebody assist me with this?

Inner Stack Trace of the Exception

 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)
1
1
9/14/2012 3:03:07 PM

Accepted Answer

Consider this. If the problems are comparable, this ought to resolve them.

Exception in the Entity Framework

4
5/23/2017 12:27:15 PM

Popular Answer

Verify that you are not storing data to the database inside foreach or anything similar.

Edit: Perhaps another iterative cycle.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow