EF Core Bulk - Native Insert

CSharp · Console

/Program.cs

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.Data.SqlClient;
using System.Linq;

public class Order
{
	public int Id { get; set; }
	public string Description { get; set; }
	public bool IsProcessed { get; set; }
    public string CustomerName { get; set; } 
    public decimal Amount { get; set; }
	public int Quantity { get; set; }
    public string Status { get; set; }
    public DateTime CreatedDate { get; set; }
	public string Address { get; set; }
	public string Notes { get; set; } 
}

public class AppDbContext : DbContext
{
	public DbSet<Order> Orders { get; set; }

	protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
	{
		optionsBuilder.UseSqlServer(new SqlConnection(FiddleHelper.GetConnectionStringSqlServer()));
		base.OnConfiguring(optionsBuilder);
	}
}

public class Program
{
	public static async Task Main()
	{
		using var context = new AppDbContext();
		// Ensure database is created
		await context.Database.EnsureCreatedAsync();
		
		if (!context.Orders.Any())
		{
			var orders = Enumerable.Range(1, 10000).Select(i => new Order
							{
								Description = $"Order {i}",
								CustomerName = $"Customer {i}",
								Quantity = i * 2,
								Amount = 10.5m * i,
								CreatedDate = DateTime.UtcNow.AddDays(-i),
								IsProcessed = i % 2 == 0,
								Address = $"Address {i}, {i} + 1",
								Notes = $"Notes {i}"
							}).ToList();
			
			var stopwatch = Stopwatch.StartNew();
			await context.Orders.AddRangeAsync(orders);
			await context.SaveChangesAsync();
			stopwatch.Stop();
			Console.WriteLine($"Inserted {orders.Count} orders");
			Console.WriteLine($"Elapsed: {Math.Round(stopwatch.Elapsed.TotalSeconds, 2)} seconds");
		}

		
	}
}
;