【问题标题】:How to change the value of associated field如何更改关联字段的值
【发布时间】:2008-10-13 14:24:27
【问题描述】:
我有 2 个类之间存在 LINQ 关联,即:
Table1: Table2:
ID ID
Name Description
ForiegnID
这里的关联是Table1.ID -> Table2.ForiegnID
我需要能够更改 Table2.ForiegnID 的值,但我不能并认为这是因为关联(当我删除它时,它会起作用)。
因此,有谁知道如何更改关联字段 Table2.ForiegnID 的值?
【问题讨论】:
标签:
c#
linq
linq-to-sql
associations
【解决方案1】:
查看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");
}
}
}
最好通过关联而不是键来分配更改。这样,您就不必担心是否加载了父级。
【解决方案2】:
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 中的记录关联
【解决方案3】:
您想与 table1 中的另一条记录关联或更改 table1.id?
如果是选项 1,则需要删除该关联并设置一个新关联。
如果选项 2,请检查您的 db 并查看是否为此 fk 启用了更新级联是,然后获取记录并更改 id 的值。