【问题标题】:How to add an element that is the child of several foreign key relations without touching the parent elements如何在不触及父元素的情况下添加作为多个外键关系的子元素的元素
【发布时间】:2012-01-04 15:58:21
【问题描述】:

我在 C# 中在 2 个元素上使用 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。 唯一性设置为 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

有什么想法吗?

【问题讨论】:

  • 绑定前有没有试过在游戏中查找并添加控制台?

标签: sql-server asp.net-mvc linq linq-to-sql


【解决方案1】:

对于 Linq,它在很大程度上是一种读取和重放模型。尝试先从 Linq 检索相关实体,然后相应地设置这些属性。然后,Linq 应该知道正确的相关性,并且重复的 FK 异常应该消失。

【讨论】:

    猜你喜欢
    • 2023-03-15
    • 1970-01-01
    • 2019-10-19
    • 1970-01-01
    • 1970-01-01
    • 2013-10-16
    • 2019-02-28
    • 2020-09-04
    • 1970-01-01
    相关资源
    最近更新 更多