Skip to main content
 首页 » 编程设计

c#之Entity Framework 异常 : New transaction is not allowed because there are other threads running in the session

2024年02月20日37EasonJim

<分区>

我正在使用从 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(); 
    } 
} 

自动刷新集合类:

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)