简体   繁体   English

如何使用对象上下文在实体框架中使用批量插入?

[英]How to use Bulk Insert in Entity Framework using Object Context?

I would like to use Object Context instead of DbContext to call Bulk Insert in Entity Framework 6. How can I do that?我想使用对象上下文而不是 DbContext 来调用实体框架 6 中的批量插入。我该怎么做?

I would like to do something like我想做类似的事情

readonly ObjectContext obContext :只读ObjectContext obContext

public void BulkInsert<T>(IEnumerable<T> items) where T : class, new()
{
    obContext.BulkInsert(items);
}

But I am not able to do this.但我无法做到这一点。

With entity framework 6, you can use this nice nuget package to bulk insert, and you can use it with the DbContext object.使用实体框架 6,您可以使用这个不错的 nuget 包进行批量插入,并且可以将它与 DbContext 对象一起使用。

so something like this:所以像这样:

using (var db = new YourDbContext())
{
   EFBatchOperation.For(db, db.BlogPosts).InsertAll(list);
}

https://github.com/MikaelEliasson/EntityFramework.Utilities https://github.com/MikaelEliasson/EntityFramework.Utilities

Hope this helps.希望这可以帮助。

With EntityFrame 6 you do insert a range of elements.使用 EntityFrame 6,您可以插入一系列元素。

For example, i add a model Customer例如,我添加了一个模型Customer

public class Customer
{
  public int Id {get; set;}
  public string CustomerName {get;set;}
  public string City {get;set;}
}

If I send List of customer from view like List of models (List), I can save range of data like:如果我从像模型列表(列表)这样的视图发送客户列表,我可以保存如下数据范围:

public ActionResult AddCustomerData(List<Customer> cust)
{
  try
  {
    using(var db = new DBContext)
    {
      db.customer.AddRange(cust);
      db.SaveChanges();
    }
  }
  catch(exception ex)
  {
  }
}

Like this you can add bulk/range of data to tha database and before adding you can modify data if you want also.像这样,您可以将大量/范围的数据添加到数据库中,并且在添加之前,您还可以根据需要修改数据。 Thank you.谢谢你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM