代码之家  ›  专栏  ›  技术社区  ›  Rami Alshareef

逻辑上为什么不能更改对象的ParentID,而必须自己更改父对象?

  •  2
  • Rami Alshareef  · 技术社区  · 14 年前
    //Set Parent ID for the rest of the Reports data sources
    this.ReportDataSources.ToList().ForEach(rds => rds.Parent = reportDataSource);
    

    为什么不能直接设置父ID?是什么让LINQ阻止了这种行为

    //Set Parent ID for the rest of the Reports data sources
    this.ReportDataSources.ToList().ForEach(rds => rds.ParentID = reportDataSource.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();
            }
        }
    }
    
    1 回复  |  直到 14 年前
        1
  •  2
  •   Marc Gravell    14 年前

    父母之间有一种不幸的口是心非;让他们不同意是一种痛苦,所以它不允许你这样做。你 可以 不过,只需设置id—特别是在插入时。

    你可以试试:

    obj.Parent = null;
    obj.ParentId = newParentId;
    

    那他们就不会有冲突了。