C#C
C#2y ago
Lamar

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:

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.
image.png
image.png
image.png
Was this page helpful?