EF扩展 - Z.EntityFramework.Extensions.EFCore ,性能提升
//安装 Z.EntityFramework.Extensions.EFCore
using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using Microsoft.Data.SqlClient; using System.Diagnostics; public class Program { public static List<BenchmarkResult> BenchmarkResults = new List<BenchmarkResult>(); public static void Main() { using (var context = new EntityContext()) { context.Database.EnsureCreated(); } JustInTime_Compile(); JustInTime_Compile(); // Generate X entities var customers = GenerateCustomers(1000); var inactiveCustomers = customers.Where(x => !x.IsActive).ToList(); var clockInsert = new Stopwatch(); var clockUpdate = new Stopwatch(); var clockDelete = new Stopwatch(); using (var context = new EntityContext()) { // BulkInsert { clockInsert.Start(); context.BulkInsert(customers); clockInsert.Stop(); BenchmarkResults.Add(new BenchmarkResult() { Action = "BulkInsert", Entities = customers.Count, Performance = clockInsert.ElapsedMilliseconds + " ms" }); } // BulkUpdate { inactiveCustomers.ForEach(x => x.Name = "zzz;" + x.Name); clockUpdate.Start(); context.BulkUpdate(inactiveCustomers); clockUpdate.Stop(); BenchmarkResults.Add(new BenchmarkResult() { Action = "BulkUpdate", Entities = inactiveCustomers.Count, Performance = clockUpdate.ElapsedMilliseconds + " ms" }); } // BulkDelete { clockDelete.Start(); context.BulkDelete(inactiveCustomers); clockDelete.Stop(); BenchmarkResults.Add(new BenchmarkResult() { Action = "BulkDelete", Entities = inactiveCustomers.Count, Performance = clockDelete.ElapsedMilliseconds + " ms" }); } } FiddleHelper.WriteTable("EFE - Easy to use, easy to customize!", BenchmarkResults); } public static void JustInTime_Compile() { var customers = GenerateCustomers(10); using (var context = new EntityContext()) { context.BulkInsert(customers); context.BulkDelete(customers); } } 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() { } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlServer(new SqlConnection(FiddleHelper.GetConnectionStringSqlServer())); base.OnConfiguring(optionsBuilder); } 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; } } }