Entity Framework 6 DbSet AddRange vs IDbSet Add - How Can AddRange be so much faster?

后端 未结 1 1019
北荒
北荒 2021-01-11 13:09

I was playing around with Entity Framework 6 on my home computer and decided to try out inserting a fairly large amount of rows, around 430k.

My first try looked li

相关标签:
1条回答
  • 2021-01-11 14:02

    As Jakub answered, calling SaveChanges after every added entity was not helping. But you would still get some performance problems even if you move it out. That will not fix the performance issue caused by the Add method.

    Add vs AddRange

    That's a very common error to use the Add method to add multiple entities. In fact, it's the DetectChanges method that's INSANELY slow.

    • The Add method DetectChanges after every record added.
    • The AddRange method DetectChanges after all records are added.

    See: Entity Framework - Performance Add


    It is perhaps not SqlBulkCopy fast, but it is still a huge improvement

    It's possible to get performance VERY close to SqlBulkCopy.

    Disclaimer: I'm the owner of the project Entity Framework Extensions

    (This library is NOT free)

    This library can make your code more efficient by allowing you to save multiples entities at once. All bulk operations are supported:

    • BulkSaveChanges
    • BulkInsert
    • BulkUpdate
    • BulkDelete
    • BulkMerge
    • BulkSynchronize

    Example:

    // Easy to use
    context.BulkSaveChanges();
    
    // Easy to customize
    context.BulkSaveChanges(bulk => bulk.BatchSize = 100);
    
    // Perform Bulk Operations
    context.BulkDelete(customers);
    context.BulkInsert(customers);
    context.BulkUpdate(customers);
    
    // Customize Primary Key
    context.BulkMerge(customers, operation => {
       operation.ColumnPrimaryKeyExpression = 
            customer => customer.Code;
    });
    
    0 讨论(0)
提交回复
热议问题