我使用批量插入插入大量记录,如 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
来自这个第 3 方项目而不是 EF6)仅支持一次批量插入到一个表。
如果您希望项目能够一次插入到多个表中以便能够处理子实体,您将需要修改代码以自己完成(如果您自己编写,请分享并贡献代码返回到项目)。
编辑:但是,这可能比您乍一看要难得多。您将无法知道在批量插入操作期间可靠地设置了哪些具有身份值的列(无论是 int
身份还是 uniqueidentifier
),因此设置 Foreign关键关系可能很难做到。您可能需要在插入之前预先设置任何标识值。
关于c# - 在 Entity Framework 中批量插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28446441/