实体框架错误为“不允许新事务,因为会话中正在运行其他线程

时间:2014-03-17 10:51:05

标签: c# multithreading entity-framework-5 entity-framework-4.1

我们正在使用实体框架codefirst方法 我是实体框架的新手,我在尝试执行时遇到错误"不允许新事务,因为会话中还有其他线程运行。

public class DatabaseBackup : IDataBackup
    {
        private readonly IMonarchDbContext m_db;
        public DatabaseBackup(IMonarchDbContext podb)
        {
            if (podb == null)
                throw new ArgumentNullException("podb");

            m_db = podb;
        }
    public DBBackupHistory GetLatestBackupHistory(DBBackupFrequency backupFrequency = DBBackupFrequency.Periodic)
        {
            DBBackupHistory result = null;
            // get the backup history of the given backuptype and populate the objects 

            var configId = m_db.DBBackupConfigurations.Where(c => c.ScheduleType == (int)backupFrequency && c.BackupStatus == 1).Distinct().Select(c => c.ConfigurationId).DefaultIfEmpty(-1).First();

            if (configId > 0)
            {
                result = m_db.DBBackupHistorys.Where(b => b.Status == 1 && b.ConfigurationId == configId).OrderByDescending(lb => lb.BackupDatetime).FirstOrDefault();
            }

            return result;
        }
public IEnumerable<DBBackupConfiguration> GetAllConfiguration()
        {
            var result = m_db.DBBackupConfigurations.Where(c => c.BackupStatus == 1).OrderByDescending(c => c.ConfigurationId);

            return result;
        }
            public void Backup(DBBackupConfiguration config, int fileIndex)
        {

        Console.WriteLine("Running DB Backup type {0} to device {1}", (DBBackupType)config.BackupType, fileIndex);

            m_db.StoredProc.SPBackup(config, fileIndex);

        }

我在另一个类中调用以下方法,如下所示

private readonly IDataBackup m_dataBackup;
public int PerformBackup(int defaultPollIntervalInMinutes = 15)
        {
            // polling interval in Minutes
            int pollInterval = defaultPollIntervalInMinutes;

            int fileIndex = getCurrentDumpFileIndex();

            // check for the backup configuration
            var configurations = m_dataBackup.GetAllConfiguration();

            foreach (var config in configurations)
            {
    var lastBackup = m_dataBackup.GetLatestBackupHistory(DBBackupFrequency.Weekly);
                    if (lastBackup == null)
                    {
                        m_dataBackup.Backup(config, fileIndex + 1);
                        break;
                    }

这是Db Context类,如下所示

 public class MonarchDbContext:DbContext,IMonarchDbContext
        { 
               private IStoredProcedure m_storedProc;

               private static object m_dbIntializerSet;

    public MonarchDbContext(string nameOrConnectionString)
                : base( nameOrConnectionString )
            {
                //-- Set the DB initializer only once.
                System.Threading.LazyInitializer.EnsureInitialized( ref m_dbIntializerSet,()=>{
                                        Database.SetInitializer<MonarchDbContext>(null);
                        //-- Give debug builds a chance to overwrite the above.
                        _SetInitializerForDebugBuilds();
                        return new object();
                    });

                Configuration.LazyLoadingEnabled = false;
                Configuration.ProxyCreationEnabled = false;

                var csb = new SqlConnectionStringBuilder( this.Database.Connection.ConnectionString );



                csb.MultipleActiveResultSets = true;
                this.Database.Connection.ConnectionString = csb.ToString();

                var objectContext = ( this as IObjectContextAdapter ).ObjectContext;
                objectContext.CommandTimeout = 3600;
            }

       #region Public "Tables"

            public IDbSet<DBBackupConfiguration> DBBackupConfigurations { get; set; }

            public IDbSet<DBBackupHistory> DBBackupHistorys { get; set; }

            public IStoredProcedure StoredProc
            {
                get
                {

                    return System.Threading.LazyInitializer.EnsureInitialized(ref m_storedProc, () => new BackupStoredProc(this.Database));
                }
            }
            #endregion

请让我知道如何解决这个问题。

2 个答案:

答案 0 :(得分:2)

我发现了问题

我需要在Linq代码的末尾添加toList(),它对我有效。

public IEnumerable<DBBackupConfiguration> GetAllConfiguration()
        {
        var result = m_db.DBBackupConfigurations.Where(c => c.BackupStatus == 1).OrderByDescending(c => c.ConfigurationId).ToList();
            return result;
        }

答案 1 :(得分:0)

只需将List添加到Ienumerable类型