【问题标题】:BulkInsertAsync from EFCore.BulkExtensions doesn't seem to insert anything来自 EFCore.BulkExtensions 的 BulkInsertAsync 似乎没有插入任何内容
【发布时间】:2021-05-07 20:07:15
【问题描述】:

我正在使用 EFCore.BulkExtensions 将最多 100,000 条记录批量插入到数据库中。

我的问题是,出于某种原因,BulkInsertAsync 没有向数据库插入任何记录。我知道这是一个异步调用,但我等了半个小时,没有插入任何数据。常规的、同步的 BulkInsert 调用有效,但由于占用了大量的处理时间,因此非常不理想。

有人知道为什么BulkInsertAsync 在这种情况下不起作用,而BulkInsert 可以吗?

这是相关代码,它将二进制数据(从另一台机器传输)编组到 C 结构中,将该 C 结构添加到列表中,然后将列表批量插入到数据库中。

            IList<object> records = new List<object>();
            using (var db = new RecordContext())
            {
                // keep going until we process all the data; numRecs is at most 100,000
                for (int i = 0; i < numRecs; i++)
                {
                    // marshal the data into the struct and map it to its database struct
                    var tempStruct = Marshal.PtrToStructure<T>(dataPtr);
                    records.Add(tempStruct);
                    dataPtr += Marshal.SizeOf<T>();
                }
                db.BulkInsertAsync(records);
            }

这里是相关的上下文代码:

    public class RecordContext : DbContext
    {
        public RecordContext() : base(GetOptions()) 
        { 
            // disable change tracking for performance
            ChangeTracker.AutoDetectChangesEnabled = false;
        }

        private static DbContextOptions GetOptions()
        {
            return SqlServerDbContextOptionsExtensions.UseSqlServer(new DbContextOptionsBuilder(), new Settings().recordsConnectionString).Options;
        }
        // . . .
    }

以下连接字符串是从设置中传入的: Data Source=localhost;Integrated Security=True;TrustServerCertificate=True;ApplicationIntent=ReadWrite;Initial Catalog=Records

【问题讨论】:

    标签: c# database entity-framework entity-framework-core efcore.bulkextensions


    【解决方案1】:

    该方法应该做一些事情 - 如果你等待它。

    所以,而不是: db.BulkInsertAsync(records); 做: await db.BulkInsertAsync(records);

    本质上,您告诉它执行异步任务,然后通过不调用 await 退出创建/拥有该任务的方法,导致该任务被放弃。异步任务有一些微妙的魔力,哈哈。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-10-13
      • 2018-01-14
      • 1970-01-01
      • 2011-06-04
      • 2019-02-02
      • 2015-08-04
      • 2010-12-24
      相关资源
      最近更新 更多