EntityFramework异常:不允许新事务,因为会话中还有其他线程在运行

时间:2012-09-14 13:06:33

标签: c# wpf sql-server entity-framework exception

我正在使用来自CodeProject的ServiceBrokerClass。但现在当我尝试使用EnityFramework和.Net WPF将任何记录保存到数据库中时。我收到以下错误。

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

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

我的代码:

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

任何人都可以帮我这个。

内部异常堆栈跟踪:

 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 个答案:

答案 0 :(得分:4)

看看这个。 如果类似的话,这应该可以解决您的问题。

Entity Framework Exception