2008-10-13 29 views
6

我有2個教學班,他們之間的LINQ關聯的關聯字段的值,即:如何改變

Table1:  Table2: 
ID   ID 
Name   Description 
       ForiegnID 

這裏的協會之間Table1.ID - > Table2.ForiegnID

我需要能夠改變Table2.ForiegnID的值,但我不能認爲這是因爲關聯(當我刪除它,它的工作原理)。

因此,有沒有人知道我可以如何更改相關字段Table2.ForiegnID的值?

回答

7

檢出designer.cs文件。這是鑰匙的財產

[Column(Storage="_ParentKey", DbType="Int")] 
public System.Nullable<int> 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<int>); 
      } 
      this.SendPropertyChanged("Parent"); 
     } 
    } 
} 

最好是通過關聯而不是密鑰分配更改。這樣,您不必擔心父級是否已加載。

+0

可能是對的東西有,請你能對 – HAdes 2008-10-13 14:51:52

0

你想與table1中的另一個記錄相關聯或更改table1.id? 如果它是選項1,則需要刪除該關聯並設置一個新關聯。 如果選項2,檢查你的數據庫,看看是否更新級聯是啓用此fk並獲取記錄和更改id的值。

1
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