I am trying to seed a OneToMany Relationship in my Database with defined List<> and I get the following Error-Msg
'The seed entity for entity type 'Country' cannot be added because it has the navigation 'WineRegions' set. To seed relationships you need to add the related entity seed to 'WineRegion' and specify the foreign key values {'CountryId'}. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the involved property values.'
I used this page to create my classes: https://www.learnentityframeworkcore.com/relationships#one-to-many ... I can only guess that I somehow need to define the keys manually even though it should work automatically...
Here are my two classes. WineRegions contains one Country and Country contains a collection of WineRegions:
public class WineRegion
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int WineRegionId { get; set; }
public string WineRegionName { get; set; }
public int CountryId { get; set; }
public Country Country { get; set; }
}
public class Country
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int CountryId { get; set; }
[Required]
[MaxLength(255)]
public string CountryName { get; set; }
[Required]
[MaxLength(2)]
public string ISO3166Alpha2 { get; set; }
public ICollection<WineRegion> WineRegions { get; set; }
}
During the Seeding I don't want to use hardcoded Objects like (btw this code works...):
modelBuilder.Entity<Country>().HasData(
new { Id = 1, Name = "France", ISO3166Alpha2 = "FR" }
);
modelBuilder.Entity<WineRegion>().HasData(
new { Id = 1, Name = "Bordeaux", CountryId = 1 }
);
As I mentioned before I want to use List which I generate during a JSON Parsing process.
So this is what I do:
modelBuilder.Entity<Country>().HasData(listOfCountries); // List<Country>
modelBuilder.Entity<WineRegion>().HasData(listOfWineRegions); //List<WineRegion>
My JSON looks like this:
"wineregions": [
{
"id": 1,
"country": "France",
"iso2": "FR",
"region": [
{
"id": 1,
"name": "Bordeaux"
},
{
"id": 2,
"name": "Burgundy"
},
{
"id": 4,
"name": "Burgundy"
},
{
"id": 5,
"name": "Beaujolais"
},
{
"id": 6,
"name": "Champagne"
},
{
"id": 7,
"name": "Loire"
},
{
"id": 8,
"name": "Alsace"
},
{
"id": 9,
"name": "Rhône"
},
{
"id": 10,
"name": "Provence"
},
{
"id": 11,
"name": "Languedoc-Roussillon"
},
{
"id": 12,
"name": "Jura"
}
]
},
{
"id": 2,
"country": "Italy",
"iso2": "IT",
"region": [
{
"id": 1,
"name": "Piedmont"
},
{
"id": 2,
"name": "Barolo"
},
{
"id": 3,
"name": "Barbaresco"
},
{
"id": 4,
"name": "Tuscany"
},
{
"id": 5,
"name": "Veneto"
},
{
"id": 6,
"name": "Friuli-Venezia"
},
{
"id": 7,
"name": "Giulia"
},
{
"id": 8,
"name": "Abruzzo"
},
{
"id": 9,
"name": "Sicily"
},
{
"id": 10,
"name": "Lambrusco"
}
]
}
]
}
Thanks in advance