using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using Microsoft.Data.SqlClient;
using System.ComponentModel.DataAnnotations;
public static void Main()
using (var context = new EntityContext())
context.Database.EnsureCreated();
using (var context = new EntityContext())
var students = new List<Student>();
var schools = new List<School>();
var registrations = new List<Registration>();
var student1 = new Student() { FirstName = "Go_To_School_A"};
var student2 = new Student() { FirstName = "Go_To_School_B"};
var student3 = new Student() { FirstName = "Go_To_School_A_B"};
var school1 = new School() { Name = "School_A"};
var school2 = new School() { Name = "School_B"};
registrations.Add(new Registration() { School = school1, Student = student1 });
registrations.Add(new Registration() { School = school2, Student = student2 });
registrations.Add(new Registration() { School = school1, Student = student3 });
registrations.Add(new Registration() { School = school2, Student = student3 });
context.BulkMerge(students);
context.BulkMerge(schools);
registrations.ForEach(x => {
x.SchoolId = x.School.SchoolId;
x.StudentId = x.Student.StudentId;
context.BulkMerge(registrations, options => {
options.ColumnPrimaryKeyExpression = m => new { m.SchoolId, m.StudentId };
FiddleHelper.WriteTable("1 - Students", context.Students.AsNoTracking().ToList());
FiddleHelper.WriteTable("2 - Schools", context.Schools.AsNoTracking().ToList());
FiddleHelper.WriteTable("3 - Registrations", context.Registrations.AsNoTracking().ToList());
public class EntityContext : DbContext
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
optionsBuilder.UseSqlServer(new SqlConnection(FiddleHelper.GetConnectionStringSqlServer()));
base.OnConfiguring(optionsBuilder);
public DbSet<School> Schools { get; set; }
public DbSet<Student> Students { get; set; }
public DbSet<Registration> Registrations { get; set; }
public class Registration
public int RegistrationId { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public int StudentId { get; set; }
public Student Student { get; set; }
public int SchoolId { get; set; }
public School School { get; set; }
public int SchoolId { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public int SchoolIdentifier { get; set; }
public int StudentId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string StudentIdentifier { get; set; }