【问题标题】:Bulk insert in entity framework在实体框架中批量插入
【发布时间】:2015-02-12 00:23:10
【问题描述】:

我使用批量插入插入大量记录,例如 20K,当我只插入一个实体时它会正常工作。但是,当我过去插入多个实体(例如一对多)时,它只会插入父实体,而不会插入子实体。

我的实体和代码

Customer.cs
    public class Customer
     {
        public Customer()
        {
           this.AccountCustomers = new HashSet<AccountCustomer>();
        }
        public int CustomerId{get;set;}
        public int CustomerName{get;set;}
        public virtual ICollection<AccountCustomer> AccountCustomers { get; set; }
     }

 AccountCustomer.cs
     public partial class AccountCustomer
      {
       public int CustomerId { get; set; }        
       public string CustomData { get; set; }
       public System.DateTime CreatedDate { get; set; }       

       public virtual Customer Customer { get; set; }
      }

My code:
  List<Customer> customerList = CreateCustomer();
  for (int index = 0; index < 20000;index++ )
        {
            Customer customer = new Customer();
            customer.CustomerName= "Parthi";
            AccountCustomer accountCustomer = new AccountCustomer();
            accountCustomer.CustomdData= "customdata";
            accountCustomer.CreatedDate = DateTime.UtcNow;
            customer.AccountCustomers.Add(accountCustomer);
            customerList.Add(customer);
        }

      private static void AddCustomer(List<Customer> customerList)
      {
        using (var ctx =new Directdialogs())
        {
            using (var transactionScope = new TransactionScope())
            {
                try
                {
                    ctx.BulkInsert(customerList);
                    ctx.SaveChanges();
                    transactionScope.Complete();
                }
                catch(Exception ex)
                {
                    transactionScope.Dispose();
                }
            }
        }
    }

这是我的代码,但它只会插入客户实体数据而不插入帐户客户数据,批量插入不支持插入多个实体,任何人都知道帮助我。

提前致谢。

【问题讨论】:

  • BulkInsert 是一种扩展方法。
  • 什么是BulkInsert?不是 EF 中的东西
  • 在Entity framework 6中的朋友。
  • It is not part of DbContext,你确定你没有安装this nuget package吗?
  • 你确定它不是 DbContext 的一部分,在我在 nuget 包中安装了这个“Install-Package EntityFramework.BulkInsert-ef6”之后。

标签: c# sql-server entity-framework


【解决方案1】:

您正在使用的EntityFramework.BulkInsert 项目(BulkInsert 来自此第 3 方项目而不是 EF6)仅支持一次批量插入一个表。

如果您希望项目能够一次插入多个表以处理子实体,您将需要修改代码以自己完成(如果您自己编写,请分享并贡献代码返回项目)。

编辑:但是,这可能比您乍一看要困难得多。您将无法知道在批量插入操作期间可靠地设置了哪些具有标识值的列(无论是 int 标识还是 uniqueidentifier),因此设置外键关系可能非常困难。您可能需要在插入之前预先设置任何标识值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多