如何更改关联字段的值

HAd*_*des 6 c# linq associations linq-to-sql

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

Table1:       Table2:
ID            ID
Name          Description
              ForiegnID
Run Code Online (Sandbox Code Playgroud)

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

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

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

Amy*_*y B 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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是协会财产.

[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");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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