2008-10-13 54 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