C# 实体框架4.0:更改主实体中的关系实体也会覆盖主实体的ID

C# 实体框架4.0:更改主实体中的关系实体也会覆盖主实体的ID,c#,entity-framework,entity,relationship,C#,Entity Framework,Entity,Relationship,我得到了一个实体“许可证”,其中包含一些关系,包括三个1..*关系。 我正在使用GUI+管理器来编辑实体并稍后再次保存它。 当我在按钮上调用save事件时,我会通过读取控件中的值来覆盖我正在编辑的预加载实体的属性和关系 通过加载具有相同ObjectContext的新选定实体并覆盖关系本身,我正在更改三个关系。在三种情况中有两种情况下,它工作得很好。即使在最后一种情况下,关系更改(存储了另一个实体)成功,保存过程也可以很好地完成。然而,在第三种情况下,有一种奇怪的行为,我不明白,也不知道如何修复它

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

通过加载具有相同ObjectContext的新选定实体并覆盖关系本身,我正在更改三个关系。在三种情况中有两种情况下,它工作得很好。即使在最后一种情况下,关系更改(存储了另一个实体)成功,保存过程也可以很好地完成。然而,在第三种情况下,有一种奇怪的行为,我不明白,也不知道如何修复它:

当我更改关系的实体时,它会覆盖许可证对象的ID,这毫无意义

代码如下:

图形用户界面:

BLL(经理):

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


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

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

以前在SQL Management Studio中创建关系时,我忘记在许可证表中设置正确的外键。因此,它仍然在ID上,并在更改关系时强制覆盖我的许可证实体的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
    //...
}
// 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 ...
}
//...