C# 从逻辑上讲,为什么可以';I don’我不能更改对象的ParentID,而是必须更改其自身的父对象?

C# 从逻辑上讲,为什么可以';I don’我不能更改对象的ParentID,而是必须更改其自身的父对象?,c#,linq-to-sql,C#,Linq To Sql,为什么我不能直接设置父ID?什么可以让LINQ阻止这样的行为 //Set Parent ID for the rest of the Reports data sources this.ReportDataSources.ToList().ForEach(rds => rds.Parent = reportDataSource); 这里抛出异常 //Set Parent ID for the rest of the Reports data sources this.ReportData

为什么我不能直接设置父ID?什么可以让LINQ阻止这样的行为

//Set Parent ID for the rest of the Reports data sources
this.ReportDataSources.ToList().ForEach(rds => rds.Parent = reportDataSource);
这里抛出异常

//Set Parent ID for the rest of the Reports data sources
this.ReportDataSources.ToList().ForEach(rds => rds.ParentID = reportDataSource.ID);
[Column(Storage=“\u ParentID”,DbType=“Int”)]
公共系统。可为空的ParentID
{
得到
{
返回此。\u ParentID;
}
设置
{
if((this.\u ParentID!=值))
{
如果(此._Parent.hasloadeOrassignedValue)
{
抛出新System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();
}
此.onParentIDChangeing(值);
此参数为.SendPropertyChanging();
这是。_ParentID=值;
此.SendPropertyChanged(“ParentID”);
this.OnParentIDChanged();
}
}
}

ParentId和Parent之间存在不幸的双重性;让他们不同意是一种痛苦,所以你不能这样做。您可以只设置id,尤其是在插入时

你可以试试:

[Column(Storage="_ParentID", DbType="Int")]
public System.Nullable<int> ParentID
{
    get
    {
        return this._ParentID;
    }
    set
    {
        if ((this._ParentID != value))
        {
            if (this._Parent.HasLoadedOrAssignedValue)
            {
                throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();
            }
            this.OnParentIDChanging(value);
            this.SendPropertyChanging();
            this._ParentID = value;
            this.SendPropertyChanged("ParentID");
            this.OnParentIDChanged();
        }
    }
}

那么它们就不会冲突。

当然我调试过了,我在代码上发布的异常:throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();,每当ParentId发生更改时就会抛出它。那么此属性的意义是什么:this.\u Parent.hasloadedorasignedvalue,因为我可以解决它?@rami-也许可以检查MSDN;我一点也不知道
obj.Parent = null;
obj.ParentId = newParentId;