简体   繁体   中英

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?

I would like to do something like

readonly 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.

so something like this:

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

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

Hope this helps.

With EntityFrame 6 you do insert a range of elements.

For example, i add a model 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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