【问题标题】:Entity Framework BulkInsert not inserting child entities实体框架 BulkInsert 不插入子实体
【发布时间】:2017-07-04 06:23:01
【问题描述】:

我有 2 张桌子 INS_Staging_UMLERTransaction(Parent)INS_Staging_UMLERBlueCard(Child)

我需要插入 1000 条记录,当我使用批量插入时,它只插入父表。以下是我的代码。

 _indnCon.BulkInsert(_DataToTrans);                                       
 _indnCon.BulkInsert(_DataToTrans.SelectMany(m => 
                      m.INS_Staging_UMLERBlueCard));
 _indnCon.BulkSaveChanges();

【问题讨论】:

    标签: asp.net-mvc entity-framework bulkinsert


    【解决方案1】:

    Entity Framework Extended 中没有 BulkInsertBulkSaveChanges 方法。

    所以在我的回答中,我假设您使用的是 Entity Framework Extensions 库。


    从 v3.12.6 (Release Note) 开始,添加了一个 IncludeGraph 选项以包含子实体。

    示例

    _indnCon.BulkInsert(_DataToTrans, operation => operation.IncludeGraph = true);  
    

    注意:您不必在调用 BulkInsert 后调用 BulkSaveChanges。批量操作直接在数据库中进行。

    回答子问题:

    我在使用 IncludeGraph 时遇到异常。例外是“A 默认 DbContext 上下文必须存在,或者上下文工厂必须存在 提供(EntityFrameworkManager.ContextFactory)。这个设置是 IncludeGraph 等某些功能需要。”

    此错误意味着您的上下文没有默认构造函数。此功能需要一种构建新上下文的方法。

    下面是一个示例,当不存在默认构造函数时如何指定上下文工厂:

    EntityFrameworkManager.ContextFactory = context => new CurrentContext(My.ConnectionString);
    

    【讨论】:

    • 我在使用 IncludeGraph 时遇到异常。例外情况是“必须存在默认 DbContext 上下文,或者必须提供上下文工厂 (EntityFrameworkManager.ContextFactory)。对于 IncludeGraph 等某些功能,此设置是必需的。”。
    • 还有一个例外,“已经为对象层类型'PRIM.InsightNucleus.Data.INS_Staging_UMLERTransaction'生成了一个代理类型。当相同的对象层类型被两个或两个映射时会发生这种情况AppDomain 中有更多不同的模型。”
    • 这里我在2 DBContext中使用这个类
    • 这就是为什么有一个“上下文”变量。通过使用 typeof(context),你可以很容易地找到我们从哪个是正确的上下文来初始化
    【解决方案2】:

    这就是我解决的方法。 Postgres 数据库已使用。

    services.AddDbContextPool<postgresContext>(options =>
     {                
         options.UseNpgsql(Configuration.GetConnectionString("PostgresConString"));
     });
    

    // 出现此类错误时添加此行

    EntityFrameworkManager.ContextFactory = context =>
     {
             var optionsBuilder = new DbContextOptionsBuilder<postgresContext>();                
             optionsBuilder.UseNpgsql(Configuration.GetConnectionString
    ("PostgresConString"));
                    return new postgresContext(optionsBuilder.Options);
    };
    

    【讨论】:

    • 这如何回答这个问题?我想你打算回答另一个问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-09
    • 2017-02-01
    • 2020-12-10
    • 2020-11-28
    • 1970-01-01
    • 2018-01-19
    • 2022-08-03
    相关资源
    最近更新 更多