title: How to save a lot of related data all at once (custom-build seeder)
body: <p>I have a .NET Core web application with a EF Core (Code-First) database on the backend. I need to seed a bunch of data into the database at once, on initialization, because the project is still in development.</p>
  
  <p>But I CAN'T get away from these FOREIGN KEY SQL exceptions! They are like a leaky pipe, every time I make a change to fix one, another pops up. And the models are so interconnected that's a lot of leaks. I need to fix them once and for all.</p>
  
  <p>I have all my models and model relationships defined, I'm using the Bogus library for C# to generate the data, I have all the code written to create bogus entities and tie them all together in the way they should be.</p>
  
  <p>I can't post my exact code because it's proprietary (I'm a contractor), but I can provide a summary of what it does:</p>
  
  <ul>
  <li>There is a DbSeeder class that runs at application startup if it has not been run before. This is where the database seeding logic is stored. Note that I am not using any of the database seeding methods described in the MSFT docs -- I didn't know about them when I wrote the seeder and I'm in too deep now.</li>
  <li>Each entity has a GenerateBogus() method defined in the DbSeeder, which will generate an object of the entity's type and set all the properties to values supplied by Bogus except relationships, no relationships are defined by the Bogus() methods.</li>
  <li>I have a single method in the DbSeeder that calls the Bogus() methods for each of the entity types, effectively generating the appropriate amount of bogus data to seed the database with. Here is what that method looks like:</li>
  </ul>
  
  <pre class="lang-cs prettyprint-override"><code>// Generation of entities
  var apples = GenerateBogusApples(5);
  var bananas = GenerateBogusBananas(20);
  
  // Add them to context
  context.Apples.AddRange(apples);
  context.SaveChanges();
  
  context.Bananas.AddRange(bananas);
  context.SaveChanges();
  
  // Set up relationships
  foreach (Bananas b in bananas)
  {
      b.Apple = apples.Random();    // little pseudocode, hope you don't mind
  }
  
  // One final
  context.SaveChanges();
  
  // End result: A banana with an apple object associated with it
  // My actual task is way more complicated, with lots of interdependency :/
  </code></pre>
  
  <p>I just need the database in a state where all the dummy data I insert into it is associated properly with related data according to the business logic. Instead I get many different kinds of Foreign Key errors, such as "The MERGE statement conflicted with the FOREIGN KEY constraint".</p>