[英]Bulk insert in entity framework
我使用批量插入插入了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();
}
}
}
}
這是我的代碼,但是它只會插入客戶實體數據而不插入客戶客戶數據,批量插入不支持插入任何人都知道的幫助我。
提前致謝。
您正在使用的EntityFramework.BulkInsert項目( BulkInsert
來自此第三方項目而不是EF6)僅一次支持批量插入一個表。
如果您希望項目能夠一次插入多個表中以處理子實體,則需要修改代碼以自己完成(如果您自己編寫,請共享並將代碼貢獻給該項目)。
編輯:但是,這可能比乍一看要難得多。 您將無法可靠地知道在批量插入操作期間將哪些Identity列(具有int
身份或uniqueidentifier
)可靠地設置在哪里,因此設置外鍵關系可能非常困難。 插入之前,您可能需要預先設置所有標識值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.