entity framework seed function did not Insert all the data to database
-
25-10-2019 - |
Question
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.
Solution
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
_CycleType.ForEach(IndividualRow => context.CycleType.Add(IndividualRow));
OTHER TIPS
You are only adding CycleModel
s to the context. When you add a CycleModel
EF will add all the related entities that CycleModel
instance keep reference to. Here the list of CycleModel
s added to the context does not have any relation to the CycleType
"Mountain Bike Type A". Hence it is not added.
You can add all the CycleType
s first.
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" }
}.ForEach(c => context.CycleType.Add(c));
Or you can add that instance separately.
context.CycleType.Add(_CycleType.Single(r => r.Type == "Mountain Bike Type A"));