2012-01-04 55 views
0

我在2個元素(對於這個問題說他們是遊戲和控制檯)在C#中使用LINQ to SQL,有一個一對多的關係(一種類型的控制檯可以用來玩很多遊戲)。如何在不觸及父元素的情況下添加幾個外鍵關係的子元素

比方說,這是我的遊戲類別:

public class Game { 
public int GameID {get; set;} ///this is the PK 
public int ConsoleID {get; set;} ///this is the FK 
public string Title {get; set;} ///this is the title of the game. 
... 
} 

,這是我的控制檯類:

public class Console { 
public int ConsoleID {get; set;} ///this is the PK 
public string ConsoleName {get; set;} ///this is the name of the console 
public int GenerationNumber {get; set;} ///this is the generation of the console. e.g: The Nintendo 64 is a 3rd generation console (after NES and SNES) 
... 
} 

在DBML文件,我有兩個類之間的關聯: 基數: OneToMany 孩子屬性是內部的,被稱爲遊戲(無修飾符) 父屬性是公共的,並且是控制檯。 參與屬性顯然是Game.ConsoleID和Console.ConsoleID。 Unique設置爲false。

我想添加一個遊戲到數據庫。這樣做後,我將所有屬性設置爲相應的值。假設遊戲是XBOX360遊戲Game.Console。 propertyname將顯示有關XBOX360的信息。

但是,當我使用服務和存儲庫將遊戲添加到數據庫(SQL Server 08)時,我在控制檯上得到一個DuplicateKeyException。正因爲如此,我認爲這意味着它試圖將已經存在的有關控制檯的信息添加到控制檯表中。很顯然,我不希望發生這種情況。

這裏是我到目前爲止已經試過:

嘗試#1:

Game.Console = null; //fails - set the ID to 0, and tried to remove the relationship) 

嘗試#2:

Game.Console = null; 
Game.ConsoleID = 6; //fails - ForeignKeyReferenceAlreadyHasValueException is thrown 

任何想法?

+2

你有沒有試圖在綁定前查找並添加到遊戲控制檯? – John 2012-01-04 16:37:28

回答

1

與Linq這是一個非常多的閱讀和重播模型。嘗試從Linq首先檢索相關實體,然後相應地設置這些屬性。然後Linq應該知道正確的相關性,重複的FK異常應該消失。

相關問題