this is my diagram
and this is my method to add food and its category .
food add to database correctly , but it does not add to foodcategorySelected table
public async Task AddFoodCategoryToFoodList(int foodId, List<int> foodCategoryId)
{
if (!foodCategoryId.Any()) return;
foreach (var foodCat in foodCategoryId)
{
FoodSelectedCategory foodSelectedCategory = new FoodSelectedCategory()
{
FoodId = foodId,
FoodCategoryId = foodCat,
RegisterDate = DateTime.Now,
};
await _foodRepository.AddFoodCategoryToFood(foodSelectedCategory);
await _foodRepository.SaveChanges();
}
}
before that I have a method to get information with food and selected category :
Food adds to database and when goes to this method, how ever it takes all Ids (food and food categories) but can not add and have this error:
my main method:
public async Task<CreateFoodResult> CreateFoodByAdmin(CreateFoodViewModel createFoodViewModel) { Food food = new Food()
{
FoodTitle = createFoodViewModel.FoodTitle.SanitizeText(),
IsActive = createFoodViewModel.IsActive,
RegisterDate = DateTime.Now,
FoodDescription = createFoodViewModel.FoodDescription.SanitizeText(),
IsDelete = true,
CreatedUser = createFoodViewModel.CreatedUser,
};
if (createFoodViewModel.FoodAvatar != null)
{
string imageName = NameGenerator.GenerateUniqCode() +
Path.GetExtension(createFoodViewModel.FoodAvatar.FileName);
createFoodViewModel.FoodAvatar.AddImageToServer(imageName, FilePath.FilePath.FoodAvatarServer, 100,
100, FilePath.FilePath.FoodAvatarThumbServer);
food.ImageFood = imageName;
}
await _foodRepository.CreateFoodByAdmin(food);
await _foodRepository.SaveChanges();
if (createFoodViewModel.SelectedFoodCategory != null)
{
await AddFoodCategoryToFoodList(food.FoodId, createFoodViewModel.SelectedFoodCategory);
await _foodRepository.SaveChanges();
}
return CreateFoodResult.Success;
}
and I see this error:
SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_FoodSelectedCategories_FoodCategories_FoodCategoryId". The conflict occurred in database "EvSef_db", table "dbo.FoodCategories", column 'FoodCategoryId'.