I would like to seed my Database with EF Core and seeding the connecting table for the many-to-many relationship doesn't work.
I've got three models:
public class Droid
{
public int DroidId { get; set; }
public string DroidName { get; set; }
}
public class Colors
{
public int ColorID { get; set; }
public string Color { get; set; }
}
public class DroidColors
{
public int DroidColorID { get; set; }
public int ColorID { get; set; }
public int DroidID { get; set; }
}
And I'm seeding the database right at the beginning. Seeding the droid table and the color table works fine, but the droidcolor table just stays emtpy.
using (var context = new DBContext(serviceProvider.GetRequiredService<DbContextOptions<DBContext>>()))
{
if (context.Colors.Any())
{
return;
}
var colors = new Color[]
{
new Color{Color = "White"},
new Parameter{Color = "Black" },
new Parameter{Color = "Orange"},
};
foreach (Color c in colors)
{
context.Colors.Add(c);
}
context.SaveChanges();
if (context.Droids.Any())
{
return;
}
var droids = new Droid[]
{
new Droid{DroidName = "R2-D2"},
new Droid{DroidName = "C-3PO"},
new Droid{DroidName = "BB-8"},
};
foreach (Droid d in droids)
{
context.Droids.Add(d);
}
context.SaveChanges();
if (context.DroidColors.Any())
{
return;
}
var droidcolors = new DroidColor[]
{
new DroidColor{DroidID = 1, ColorID = 1},
new DroidColor{DroidID = 1, ColorID = 2},
new DroidColor{DroidID = 2, ColorID = 1},
new DroidColor{DroidID = 2, ColorID = 2},
new DroidColor{DroidID = 2, ColorID = 3},
new DroidColor{DroidID = 3, ColorID = 1},
new DroidColor{DroidID = 3, ColorID = 3}
};
foreach (DroidColor DC in droidcolors)
{
context.Droids.Add(DC);
}
context.SaveChanges();
What am I missing? EF Core seems to ignore my third data array, after working with the first and the second as expected.