C# “s已打开”,您在哪一行得到此错误?使用您提供的代码,看起来您打开了一个新的连接,所以我怀疑这里发生了错误。@JonathanMagnan添加更多代码:我在BulkInsert at line connection.open()中得到了错误;我能想到的唯一

C# “s已打开”,您在哪一行得到此错误?使用您提供的代码,看起来您打开了一个新的连接,所以我怀疑这里发生了错误。@JonathanMagnan添加更多代码:我在BulkInsert at line connection.open()中得到了错误;我能想到的唯一,c#,entity-framework,C#,Entity Framework,“s已打开”,您在哪一行得到此错误?使用您提供的代码,看起来您打开了一个新的连接,所以我怀疑这里发生了错误。@JonathanMagnan添加更多代码:我在BulkInsert at line connection.open()中得到了错误;我能想到的唯一一件事,也是很难做到的,就是你得到了一个比赛条件。你能和我开个玩笑,在批量插入方法周围添加一个锁(..),看看问题是否仍然存在吗?基本上,我所做的是在insertBulk之前处理上下文,然后重新创建上下文。这解决了我的问题。太好了;)顺便说一句


“s已打开”,您在哪一行得到此错误?使用您提供的代码,看起来您打开了一个新的连接,所以我怀疑这里发生了错误。@JonathanMagnan添加更多代码:我在BulkInsert at line connection.open()中得到了错误;我能想到的唯一一件事,也是很难做到的,就是你得到了一个比赛条件。你能和我开个玩笑,在批量插入方法周围添加一个
锁(..)
,看看问题是否仍然存在吗?基本上,我所做的是在insertBulk之前处理上下文,然后重新创建上下文。这解决了我的问题。太好了;)顺便说一句,我是Z.EntityFramework.Extensions库的所有者,所以如果您需要更多帮助来实现它,请不要不好意思直接问我我使用过它,并且与试用版配合得很好。。。我问我的经理我们是否能拿到驾照,但我不知道我们是否能拿到。但这是一个伟大的产品。
    public class UnitOfWork<TContext> : Disposable, IUnitOfWork<TContext> where TContext : DbContext, new()
    {

        private  DbContext _context;
        private bool _disposed;

        private IGenericRepository<Log> _logRepository;

        // other generic repositories

        public UnitOfWork()
        {
            _context = new TContext();
        }

        public IGenericRepository<Log> LogRepository 
            => _logRepository ?? (_logRepository = new GenericRepository<Log>(_context));


        //getters for other repositories


        //------------Public Function --------------------------------
        public void Save()
        {
            _context.SaveChanges();
        }
        // this is the bulkInsert using SqlBulkCopy 
        //but getting error on the transactionscope due to opening a new connection
        public virtual void BulkInsert<T>(DbContextTransaction tx, string tableName, System.Data.DataTable dataTable)
        {
            if (!Regex.IsMatch(dataTable.TableName, @"^[A-Za-z0-9\._]+$"))
            {
                return;
            }

            SqlTransaction sqlTx = (SqlTransaction)tx?.UnderlyingTransaction;

            var columnNames =
                _context.Database.SqlQuery<SysColumns>("SELECT c.Name, t.name as Type FROM sys.columns c JOIN sys.types t ON c.user_type_id = t.user_type_id WHERE object_id = OBJECT_ID('" + dataTable.TableName + "')");

            if (columnNames == null)
            {
                return;
            }

            var connectionString = _context.Database.Connection.ConnectionString;
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                connection.Open();
                using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection, SqlBulkCopyOptions.Default, sqlTx))
                {
                    bulkCopy.DestinationTableName = tableName;
                    bulkCopy.BulkCopyTimeout = (int) TimeSpan.FromMinutes(10).TotalSeconds;

                    foreach (var column in dataTable.Columns)
                    {
                        var dbColumn =
                                columnNames.FirstOrDefault(x => string.Equals(x.Name, column.ToString(), StringComparison.CurrentCultureIgnoreCase));

                        if (dbColumn != null)
                        {
                            bulkCopy.ColumnMappings.Add(column.ToString(), dbColumn.Name);
                        }
                    }

                    bulkCopy.WriteToServer(dataTable);
                }
                connection.Close();
            }
        }

        private void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                if (disposing)
                {
                    _context.Dispose();
                }
            }
            _disposed = true;
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

    }
}
    public void ProcessData()
    {

        using (var transaction = new TransactionScope())
        {
            try
            {
                _repository.LogRepository.Insert(//log to initial import data)

                ImportData(); 

               _repository.LogRepository.Insert(//log to Complete import data)
                _repository.Save();                   
            }
            catch (Exception e)
            {
                transaction.Dispose();

            }
        }
    }

     private void ImportData()
    {
        //Creating object of datatable  
        var tblcsv =
            new DataTable("dbo.Table") { CaseSensitive = false };

        //getting full file path of Uploaded file  
        var csvFilePath = _dataImportModel.RootPath + "\\Collector\\" + "data.csv";

        //Reading All text  
        var readCsv = File.ReadAllText(csvFilePath);

        foreach (var csvRow in readCsv.Split('\n'))
        {
                foreach (var fileColumn in csvRow.Split(','))
                {
                    tblcsv.Columns.Add(fileColumn);
                }
                break;

        }

        //spliting row after new line  
        var rows = readCsv.Split('\n');
        foreach (var csvRow in rows)
        {
            if (!string.IsNullOrEmpty(csvRow))
            {

                var count = 0;
                var columnsData = SplitCsv(csvRow);

                    //Adding each row into datatable  
                    tblcsv.Rows.Add();
                    foreach (var fileRec in columnsData)
                    {
                        tblcsv.Rows[tblcsv.Rows.Count - 1][count] =
                            string.IsNullOrEmpty(fileRec) ? null : fileRec;
                        count++;
                    }

            }
        }

        _repository.BulkInsert<DataTable>(null,  "dbo.Table", tblcsv);
    }
using (var context = new CurrentContext())
{
    using (var scope = new TransactionScope())
    {
        context.Database.Connection.Open();
        using (var connection = new SqlConnection(context.Database.Connection.ConnectionString))
        {
            connection.Open();
            using (var command = new SqlCommand("SELECT 1", connection))
            {
                var x = command.ExecuteNonQuery();
            }
        }

    }      
}