如何更改关联字段的值

我有2个类,它们之间有LINQ关联,即:

Table1: Table2: ID ID Name Description ForiegnID 

这里的关联是在Table1.ID – > Table2.ForiegnID之间

我需要能够更改Table2.ForiegnID的值,但我不能并且认为这是因为关联(因为当我删除它时,它工作)。

因此,有谁知道如何更改相关字段Table2.ForiegnID的值?

查看designer.cs文件。 这是关键的财产

 [Column(Storage="_ParentKey", DbType="Int")] public System.Nullable ParentKey { get { return this._ParentKey; } set { if ((this._ParentKey != value)) { //This code is added by the association if (this._Parent.HasLoadedOrAssignedValue) { throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException(); } //This code is present regardless of association this.OnParentKeyChanging(value); this.SendPropertyChanging(); this._ParentKey = value; this.SendPropertyChanged("ParentKey"); this.OnServiceAddrIDChanged(); } } } 

这是协会财产。

 [Association(Name="Parent_Child", Storage="_Parent", ThisKey="ParentKey", IsForeignKey=true, DeleteRule="CASCADE")] public Parent Parent { get { return this._Parent.Entity; } set { Parent previousValue = this._Parent.Entity; if (((previousValue != value) || (this._Parent.HasLoadedOrAssignedValue == false))) { this.SendPropertyChanging(); if ((previousValue != null)) { this._Parent.Entity = null; previousValue.Exemptions.Remove(this); } this._Parent.Entity = value; if ((value != null)) { value.Exemptions.Add(this); this._ParentKey = value.ParentKey; } else { this._ParentKey = default(Nullable); } this.SendPropertyChanged("Parent"); } } } 

最好通过关联而不是密钥来分配更改。 这样,您不必担心父项是否已加载。

 Table1: Table2: ID ID Name Description ForeignID 

有了这个 :

Table2.ForeignID = 2

你收到一个错误……….

示例:

您可以在表2中更改ForeignID字段:

  Table2 table = dataContext.Table2.single(d => d.ID == Id) table.Table1 = dataContext.Table1.single(d => d.ID == newId); 

如果变量newId是表2中记录的id,您希望将表1中的记录关联起来

你想与table1中的另一条记录关联或更改table1.id? 如果是选项1,则需要删除该关联并设置新关联。 如果选项2,请检查db并查看是否为此fk启用了更新级联是,而不是获取记录和更改id的值。