如何更改关联字段的值

本文关键字:字段 关联 何更改 | 更新日期: 2023-09-27 17:48:49

我有两个类,它们之间有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<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");
        }
    }
}

最好通过关联而不是键来分配更改。这样,您就不必担心父对象是否已加载。

Table1:       Table2:
ID            ID
Name          Description
              ForeignID

有了这个:

表2.ForeignID=2

您收到错误。。。。。。。。。。

示例:

您可以将表2中的ForeignID字段更改为:

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

其中,变量newId是表2中要与表1中的记录关联的记录的id。

您想与table1中的另一条记录关联还是更改table1.id?如果是选项1,则需要删除该关联并设置一个新关联。如果选项2,请检查您的数据库,并查看是否为此fk启用了更新级联"是",然后获取id的记录和更改值。