title: Better way to Seed a Dot Net Core Entity Framework Database?
body: <p>I'm working to seed a database I'm creating for a United Way I'm volunteering for. (Check out TapRoot+ if you are interested in volunteering and applying some learning)</p>
  
  <p>Anyways, I'm only seeding one to many fields right now, but I've gotten it to work one table at a time.</p>
  
  <pre><code>public class Seed
  {
      private CharEmContext _context;
  
      public Seed(CharEmContext context)
      {
          _context = context;
      }
  
      public async Task SeedCounty()
      {
          if (!_context.Counties.Any())
          {
              _context.AddRange(_counties);
              await _context.SaveChangesAsync();
          }
      }...`
  </code></pre>
  
  <p>and </p>
  
  <pre><code>static List&lt;County&gt; _counties = new List&lt;County&gt;
      {
          new County { Name = "Emmet"},
          new County { Name = "Charlevoix"},
          new County { Name = "Antrim"},
          new County { Name = "Cheboygan"},
          new County { Name = "Otsego"},
          new County { Name = "None"}
      };
  </code></pre>
  
  <p>But run into trouble when I'm trying to reference the Id's assigned once they are created.</p>
  
  <p>Neither this: </p>
  
  <pre><code>static List&lt;City&gt; _cities = new List&lt;City&gt;
  {
     new City { Name = "Alanson", CountyId = _context.Counties.Where(x=&gt;x.Name =="Emmet").Select(x =&gt; x.Id).FirstOrDefault()}, ... }
  </code></pre>
  
  <p>Nor this:</p>
  
  <pre><code>static List&lt;City&gt; _cities = new List&lt;City&gt;
  {
      new City { Name = "Alanson", CountyId = _counties.Where(x=&gt;x.Name =="Emmet").Select(x =&gt; x.Id).FirstOrDefault()},
  </code></pre>
  
  <p>works.  </p>
  
  <p>For reference I'm creating a service in my <code>startup.cs.ConfigureServices</code></p>
  
  <p>services.AddTransient();</p>
  
  <p>and calling each add method in the <code>.Configure(Seed Seeder)</code></p>
  
  <pre><code>public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, Seed seeder)
  {
      seeder.SeedCounty().Wait();
      seeder.SeedCity().Wait();
      seeder.SeedLocation().Wait();
  </code></pre>
  
  <p>Definitely need to know how to reference those IDs the DB creates on the dependent tables.</p>
  
  <p>Also curious if I need to seed the linking tables in the many-to-many relationships...</p>