CodexBloom - Programming Q&A Platform

C# - Difficulty with Entity Framework Core and Bulk Insert performance optimization

πŸ‘€ Views: 616 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-14
entity-framework-core performance bulk-insert C#

I'm trying to figure out I'm stuck trying to I'm learning this framework and Quick question that's been bugging me - I'm currently working with important performance optimization when attempting to perform bulk inserts using Entity Framework Core 6.0..... I have a list of 10,000 entities that I need to insert into the database, but the operation is taking an unexpectedly long time, often over several minutes. I've tried using `AddRange` method, but it seems to be quite slow. Here’s an example of how I’m currently implementing it: ```csharp var entities = new List<MyEntity>(); for (int i = 0; i < 10000; i++) { entities.Add(new MyEntity { Name = "Entity " + i }); } dbContext.MyEntities.AddRange(entities); await dbContext.SaveChangesAsync(); ``` I also attempted to disable change tracking before the bulk insert to see if that would help with performance: ```csharp dbContext.ChangeTracker.AutoDetectChangesEnabled = false; ``` However, the performance improvement was minimal. Additionally, I noticed that when I try to insert in smaller batches (e.g., 1000 entities at a time) using a loop, the performance doesn't improve much, and it still takes a long time to complete the operation. Is there a better approach or best practice for performing bulk inserts with Entity Framework Core that could help improve this performance? Are there any specific libraries or patterns that I should be considering? Any recommendations would be greatly appreciated! What am I doing wrong? I'm working on a service that needs to handle this. I've been using C# for about a year now. What would be the recommended way to handle this? This is my first time working with C# stable. What would be the recommended way to handle this?