I have a class which inherit from DropCreateDatabaseIfModelChanges.
public class SetupData : DropCreateDatabaseIfModelChanges<CyclingClubContext>
{
protected override void Seed(CyclingClubContext context)
{
var _CycleType = new List<CycleType>
{
new CycleType { Type = "Leisure Cycle Type A" },
new CycleType { Type = "Mountain Bike Type A" },
new CycleType { Type = "Racer" },
new CycleType { Type = "Leisure Cycle Type B" },
new CycleType { Type = "Mountain Bike Type B" }
};
new List<CycleModel>
{
new CycleModel{ Model = "Challenge 26in", CycleType = _CycleType.Single(r => r.Type == "Racer") },
new CycleModel{ Model = "Challenge 27in", CycleType = _CycleType.Single(r => r.Type == "Racer") },
new CycleModel{ Model = "Muddy Fox Vortex", CycleType = _CycleType.Single(r => r.Type == "Leisure Cycle Type A") },
new CycleModel{ Model = "Laser 8", CycleType = _CycleType.Single(r => r.Type == "Leisure Cycle Type B") },
new CycleModel{ Model = "Silverfox 26in", CycleType = _CycleType.Single(r => r.Type == "Mountain Bike Type B") }
}.ForEach(IndividualRow => context.CycleModel.Add(IndividualRow));
}
}
After I run this class, I found that …
Two tables created.
1)Cycle Model (all row inserted correctly).
2)Cycle Type (One row left to insert)[Problem].
Mountain Bike Type A is not insert to table CycleType.
I think , I need to modify my code but I don’t know how could I do it.
I don’t want to insert another row like below so that it can solve my problem.
new CycleModel{ Model = "Testing...", CycleType = _CycleType.Single(r => r.Type == "Mountain Bike Type A") }
Please let me get suggestion.
A Seed() method should end with a
context.SaveChanges().As it stands now it’s strange anything is saved at all.
But it’s clear that “Mountain Bike Type A” is not referenced by any CycleModel and that is why it’s left out.
You can probably fix it with