Entity Framework Core 8 -Foreign Key Constraint failure.
Hello, I am playing around with EF code first and I am trying to model 3 tables:
I can add 1 Product entity to the DailyNutrition collection, but if I try to add more I am getting the "Foreign Key Constraint" error.
To be honest it's unclear to me which FK is referring to.
Product newProduct = new()
{
Id = guid,
CreatedAt = DateTime.Now,
UpdatedAt = DateTime.Now,
Name = ProductNutritionModel.Product.Name,
Weight = 10,
IsVegan = false,
IsVegetarian = false,
Rating = Random.Shared.Next(1, 10),
NutritionalValue = new NutritionalValue
{
EnergeticValue = 10,
Fat = 50,
SaturatedFats = 30,
Carbohydrate = 40,
Sugar = 20,
Protein = Random.Shared.Next(15, 100),
Salt = Random.Shared.Next(12, 100),
ProductId = guid
}
};
if (existingDNI is not null)
{
existingDNI.Products.Add(newProduct);
foreach (var existingDniProduct in existingDNI.Products)
{
existingDniProduct.DailyNutritionInfoId = existingDniProduct.Id;
}
var saveResult = await DbContext.SaveChangesAsync();
if (saveResult > 0)
{
Navigation.NavigateTo("");
}
}
else
{
DailyNutritionInfo newDailyNutritionInfo = new()
{
Id = Guid.NewGuid(),
CreatedAt = DateTime.Today,
Products = [newProduct],
};
DbContext.DailyNutritionInfos.Add(newDailyNutritionInfo);
var result = await DbContext.SaveChangesAsync();
if (result > 0)
{
Navigation.NavigateTo("");
}
}Product newProduct = new()
{
Id = guid,
CreatedAt = DateTime.Now,
UpdatedAt = DateTime.Now,
Name = ProductNutritionModel.Product.Name,
Weight = 10,
IsVegan = false,
IsVegetarian = false,
Rating = Random.Shared.Next(1, 10),
NutritionalValue = new NutritionalValue
{
EnergeticValue = 10,
Fat = 50,
SaturatedFats = 30,
Carbohydrate = 40,
Sugar = 20,
Protein = Random.Shared.Next(15, 100),
Salt = Random.Shared.Next(12, 100),
ProductId = guid
}
};
if (existingDNI is not null)
{
existingDNI.Products.Add(newProduct);
foreach (var existingDniProduct in existingDNI.Products)
{
existingDniProduct.DailyNutritionInfoId = existingDniProduct.Id;
}
var saveResult = await DbContext.SaveChangesAsync();
if (saveResult > 0)
{
Navigation.NavigateTo("");
}
}
else
{
DailyNutritionInfo newDailyNutritionInfo = new()
{
Id = Guid.NewGuid(),
CreatedAt = DateTime.Today,
Products = [newProduct],
};
DbContext.DailyNutritionInfos.Add(newDailyNutritionInfo);
var result = await DbContext.SaveChangesAsync();
if (result > 0)
{
Navigation.NavigateTo("");
}
}I can add 1 Product entity to the DailyNutrition collection, but if I try to add more I am getting the "Foreign Key Constraint" error.
To be honest it's unclear to me which FK is referring to.


