2010-05-20 126 views
0

考慮以下表(在Visual Studio DBML文件編輯器的截圖):LINQ到SQL - 插入實體關係

http://roosteronacid.com/dbml.png

IngredientsRecipesRelation表是許多一對多表,鏈接n配料到單一配方。


你怎麼會插入以下幾招...:

Recipe { Name = "Dough" } 

以下成分...:

Ingredient { Name = "water", Unit = "cups", Amount = 2.0 }, 
Ingredient { Name = "flour", Unit = "cups", Amount = 6.0 }, 
Ingredient { Name = "salt", Unit = "teaspoon", Amount = 2.0 } 

...到數據庫?

+0

我可能是錯的,但我不認爲Linq 2 SQL支持多對多關係。 – azamsharp 2010-05-20 14:28:01

+0

@azamsharp - 不是直接的,但可以使用兩個一對多關係來獲得相同的效果。 – tvanfosson 2010-05-20 14:36:37

+0

您的圖像損壞 – 2015-12-21 11:52:59

回答

1

創建配方和成分,然後爲每種成分創建與成分相關的關係。將這些關係中的每一個添加到配方並將配方插入到數據庫中。

var recipe = new Recipe { Name = "Dough" }; 

var ingredients = new [] 
{ 
    new Ingredient { Name = "water", Unit = "cups", Amount = 2.0 }, 
    new Ingredient { Name = "flour", Unit = "cups", Amount = 6.0 }, 
    new Ingredient { Name = "salt", Unit = "teaspoon", Amount = 2.0 } 
}; 

foreach (var ingredient in ingredients) 
{ 
    var relation = new IngredientsRecipesRelations(); 

    relation.Ingredient = ingredient; 

    recipe.IngredientsRecipesRelations.Add(relation); 
} 

DataContext.Recipes.InsertOnSubmit(recipe); 
DataContext.SubmitChanges(); 

請注意,您可以使用方法添加部分類實現,以從使用它的類中隱藏此行爲。您想要在內部作出關聯作用域範圍,然後公開一些公開方法,以添加/刪除與內部關聯一起使用的成分,如上所示。

0

azamsharp是正確的,因爲它不支持多對多,然而這link在某種程度上表明它是如何完成的,基本上你將手工編寫一些代碼