CSharp · Console
// Entity Framework Extensions
// Doc: https://entityframework-extensions.net/bulk-savechanges
// @nuget: Z.EntityFramework.Extensions
// @nuget: EntityFramework
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Data.Entity;
using System.Threading;
using System.Threading.Tasks;
public class Program
{
public static List<BenchmarkResult> BenchmarkResults = new List<BenchmarkResult>();
public static void Main()
{
MainAsync().Wait();
}
public static async Task MainAsync()
{
JustInTime_Compile();
//await JustInTime_Compile();
// Generate X entities
var customers = GenerateCustomers(1000);
var clockSaveChanges = new Stopwatch();
var clockBulkSaveChanges = new Stopwatch();
using (var context = new EntityContext())
{
// SaveChangesAsync
context.Customers.AddRange(customers);
clockSaveChanges.Start();
context.SaveChanges();
//await context.SaveChangesAsync();
clockSaveChanges.Stop();
BenchmarkResults.Add(new BenchmarkResult() { Action = "SaveChangesAsync (Entity Framework)", Entities = customers.Count, Performance = clockSaveChanges.ElapsedMilliseconds + " ms" });
}
using (var context = new EntityContext())
{
// BulkSaveChangesAsync
context.Customers.AddRange(customers);
clockBulkSaveChanges.Start();
await context.BulkSaveChangesAsync();
clockBulkSaveChanges.Stop();
BenchmarkResults.Add(new BenchmarkResult() { Action = "BulkSaveChangesAsync", Entities = customers.Count, Performance = clockBulkSaveChanges.ElapsedMilliseconds + " ms" });
}
FiddleHelper.WriteTable("EFE - High-performance bulk operations", BenchmarkResults);
}
public static async Task JustInTime_Compile()
{
var customers = GenerateCustomers(20);
// SaveChangesAsync
using (var context = new EntityContext())
{
context.Customers.AddRange(customers);
await context.SaveChangesAsync();
context.Customers.RemoveRange(customers);
await context.SaveChangesAsync();
}
// BulkSaveChangesAsync
using (var context = new EntityContext())
{
context.Customers.AddRange(customers);
await context.BulkSaveChangesAsync();
context.Customers.RemoveRange(customers);
await context.BulkSaveChangesAsync();
}
}
public static List<Customer> GenerateCustomers(int count)
{
var list = new List<Customer>();
for(int i = 0; i < count; i++)
{
list.Add(new Customer() { Name = "Customer_" + i, Description = "Description_" + i, IsActive = i % 2 == 0 });
}
return list;
}
public class EntityContext : DbContext
{
public EntityContext() : base(FiddleHelper.GetConnectionStringSqlServer())
{
}
public DbSet<Customer> Customers { get; set; }
}
public class Customer
{
public int CustomerID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public Boolean IsActive { get; set; }
}
public class BenchmarkResult
{
public string Action { get; set; }
public int Entities { get; set; }
public string Performance { get; set; }
}
}