2012-01-04 54 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异常应该消失。

相关问题