【问题标题】:entity framework 4.0: changing relationship entity in the main entity also overwrites ID of the main entity实体框架 4.0:更改主实体中的关系实体也会覆盖主实体的 ID
【发布时间】:2012-10-23 11:03:33
【问题描述】:

我有一个实体“许可证”,其中包含一些关系,包括三个 1..* 关系。 我正在开发一个 GUI + 管理器,以允许稍后编辑实体并再次保存它。 当我在按钮上调用保存事件时,我通过读取控件中的值来覆盖我正在编辑的预加载实体的属性和关系。

我通过加载具有相同 ObjectContext 的新选定实体并覆盖关系本身来更改三个关系。在 3 个案例中的 2 个中,它可以完美运行。即使在最后一种情况下,关系也已成功更改(存储了另一个实体),并且可以很好地完成保存过程。但是,在第三种情况下,有一个奇怪的行为,我不明白也不知道如何解决它:

当我更改关系的实体时,它会覆盖我的 LICENSE 对象的 ID,这完全没有意义。

代码如下:

图形界面:

private LICENSE lizenz { get; set; } // in the load event, this object will be filled correctly

private string form2obj() // this method is getting called in my button save event
{
    //...
    // I removed some conditions (they all successed on testing, so believe my controls are set right on testing this
    this.lizenz.ADRESSE_KONTAKTE_Lieferant = LizenzManager.LoadContact(Convert.ToInt32(this.ddLieferantAnsp.SelectedValue)); // ADRESSE_KONTAKTE_Lieferant is a 1..* relationship, this.ddLieferantAnsp.SelectedValue contains the ID of the object I want to load into the relationship
    this.lizenz.ADRESSE_KONTAKTE_Betreiber = LizenzManager.LoadContact(Convert.ToInt32(this.ddBetreiberAnsp.SelectedValue)); // ADRESSE_KONTAKTE_Betreiber is a 1..* relationship, this.ddBetreiberAnsp.SelectedValue contains the ID of the object I want to load into the relationship
    this.lizenz.DB_TYPES = LizenzManager.LoadDatabaseType(Convert.ToInt32(this.ddDatenbanktyp.SelectedValue)); // DB_TYPES is a 1..* relationship, too, this.ddDatenbanktyp.SelectedValue contains the ID of the object I want to load into the relationship
    // last line overwrites this.lizenz.ID with the value of Convert.ToInt32(this.ddDatenbanktyp.SelectedValue), this is wrong
    //...
}

BLL (LizenzManager):

// context is the same ObjectContext in all three calls!
//...
public static ADRESSE_KONTAKTE LoadContact(int id)
{
    return context.ADRESSE_KONTAKTE.Where(x => x.ID == id).Single(); // this seems to success
}

public static DB_TYPES LoadDatabaseType(int id)
{
    return context.DB_TYPES.Where(x => x.ID == id).Single(); // this works, but it overwrites the ID of my LICENSE object I load this into ...
}
//...

如您所见,加载方式几乎相同,两个表都有 ID 列,但最后一个关系用我加载的 DB_TYPES 实体的 ID 覆盖 this.lizenz.ID。

你能解释一下,如何解决这个问题吗?

【问题讨论】:

    标签: c# entity-framework entity relationship


    【解决方案1】:

    好的,这是一个非常小而愚蠢的问题。

    之前在 SQL Management Studio 中创建关系时,我忘记在我的 LICENSE 表中设置正确的外键。所以它仍然在 ID 上,并在更改关系时强制覆盖我的许可证实体的 ID。

    感谢所有花时间阅读此问题的人。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-24
      • 1970-01-01
      相关资源
      最近更新 更多