C# - 实体框架 - 使用外键插入数据

时间:2014-07-21 12:23:37

标签: c# linq entity-framework

这是数据库架构:

CREATE TABLE Recipe (
id int not null identity(1,1) primary key,
title varchar(140) not null,
preparationTime int not null,
cookingTime int not null,
difficulty varchar(25) not null,
picture varchar(140) not null,
nbStars float not null,
nbPersons int not null,
description varchar(5000) not null,
ingredientsDescription varchar(800) not null,
mailFacebook varchar(60) not null
);

ALTER TABLE Recipe
ADD Constraint preparationTimeLessThan0 CHECK(preparationTime > 0);

ALTER TABLE Recipe
ADD Constraint cookingTimeLessThan0 CHECK(cookingTime > 0);

ALTER TABLE Recipe
ADD Constraint nbStarsLessThan0 CHECK(nbStars >= 0 AND nbStars < 6);

ALTER TABLE Recipe
ADD Constraint nbPersonsLessThan1 CHECK(nbPersons > 0);

CREATE TABLE Ingredient (
id int not null identity(1,1) primary key,
name varchar(50) not null,
htmlName varchar(70) not null,
refCategory int not null,
FOREIGN KEY(refCategory) REFERENCES Category
);

CREATE TABLE IngredientRecipe (
idRecipe int not null,
idIngredient int not null,
PRIMARY KEY(idRecipe,idIngredient),
FOREIGN KEY(idRecipe) REFERENCES Recipe,
FOREIGN KEY(idIngredient) REFERENCES Ingredient
);

我的代码的一部分:

//creation de la recette
Recipe currentRecipe = new Recipe();
currentRecipe.title = title;
currentRecipe.picture = pictureName;
currentRecipe.nbPersons = recipeNbPersons;
currentRecipe.Category = category;
currentRecipe.nbStars = quality;
currentRecipe.difficulty = difficulty;
currentRecipe.description = preparation;
currentRecipe.cookingTime = cookingTime;
currentRecipe.preparationTime = prepaTime;
currentRecipe.mailFacebook = "me@email.com";
//currentRecipe.Ingredients = ingredientRecipeList;

foreach (Ingredient ingred in ingredientRecipeList) {
        currentRecipe.Ingredients.Add(ingred);
        System.Diagnostics.Debug.WriteLine("id : " + ingred.id + " name : " + ingred.name);
}
currentRecipe.ingredientsDescription = ingredients.ToString();

//printContent(title, ingredientRecipeList);
using (Entities entitie = new Entities())
{
      entitie.Recipes.Add(currentRecipe);
      entitie.SaveChanges();                       
}

当我在我的数据库中添加食谱时,我的食谱记录得很好,但我没有合适的食谱成分。然而,在我做了SaveChanges之前,当我打印不同配方的不同成分(包含在ingredientRecipeList中)时,成分是正确的。

我在打印配方成分之前保存在数据库中的示例      id:6088名称:aubergine(s)      id:6094名称:carotte(s)      id:6068名字:huile d&#39;橄榄      id:6077名称:poivre      id:6384名字:cumin

在我的IngredientRecipe表数据库中,当我打印配方的不同成分时,我得到了这个。 idIngredient就像一个auto_increment属性。我不明白为什么:

 idRecipe   idIngredient
   1341        8777
   1341        8778
   1341        8779
   1341        8780
   1341        8781

你有解决方案吗?

谢谢

0 个答案:

没有答案