using System.Collections.Generic;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
public static void Main()
using (var context = new EntityContext())
context.Database.EnsureCreated();
using (var context = new EntityContext())
context.Results.RemoveRange(context.Results);
context.Profiles.RemoveRange(context.Profiles);
context.BulkSaveChanges();
using (var context = new EntityContext())
var profile = new Profile() { Number = 1 };
profile.Results = new List<Result>();
profile.Results.Add(new Result() { Number = 2 });
profile.Results.Add(new Result() { Number = 3 });
context.Profiles.Add(profile);
context.BulkSaveChanges();
using (var context = new EntityContext())
var profiles = context.Profiles.Include(x => x.Results).ToList();
profiles.First().Results.Add(new Result() { Number = 10 });
profiles.Add(new Profile { Number = 11, Results = new List<Result>() { new Result { Number = 12 } } });
profiles.Add(new Profile { Number = 13, Results = new List<Result>() { new Result { Number = 14 }, new Result { Number = 15 } } });
profiles.ForEach(x => x.Id = -1);
context.BulkInsert(profiles, options =>
options.InsertIfNotExists = true;
options.ColumnPrimaryKeyExpression = x => new { x.Number };
profiles.RemoveAll(x => x.Id == -1);
profiles.SelectMany(x => x.Results).ToList().ForEach(x => x.Profiles?.RemoveAll(x => x.Id == -1));
context.BulkInsert(profiles, options =>
options.IncludeGraph = true;
options.IncludeGraphOperationBuilder = operation =>
if (operation is BulkOperation<Profile>)
var bulk = (BulkOperation<Profile>)operation;
else if (operation is BulkOperation<Result>)
var bulk = (BulkOperation<Result>)operation;
bulk.InsertIfNotExists = true;
bulk.ColumnPrimaryKeyExpression = x => new { x.Number };
FiddleHelper.WriteTable(context.Profiles.AsNoTracking().Include(x => x.Results).ToList());
public class EntityContext : DbContext
public DbSet<Result> Results { get; set; }
public DbSet<Profile> Profiles { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
optionsBuilder.UseSqlServer(new SqlConnection(FiddleHelper.GetConnectionStringSqlServer()));
base.OnConfiguring(optionsBuilder);
protected override void OnModelCreating(ModelBuilder modelBuilder)
modelBuilder.Entity<Result>()
.HasMany(e => e.Profiles)
.WithMany(e => e.Results);
base.OnModelCreating(modelBuilder);
public int Id { get; set; }
public int Number { get; set; }
public List<Profile> Profiles { get; set; }
public int Id { get; set; }
public int Number { get; set; }
public List<Result> Results { get; set; }