c# - 从逻辑上讲,为什么不能更改对象的 ParentID,而我必须自己更改父对象?

标签 c# linq-to-sql

//Set Parent ID for the rest of the Reports data sources
this.ReportDataSources.ToList().ForEach(rds => rds.Parent = reportDataSource);

为什么不能直接设置Parent 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();
        }
    }
}

最佳答案

不幸的是,ParentId 和 Parent 之间存在口是心非;让他们不同意是一种痛苦,所以它不会让你那样做。不过,您可以只设置 id - 尤其是在插入时。

你可以试试:

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

那么他们就不会发生冲突。

关于c# - 从逻辑上讲,为什么不能更改对象的 ParentID,而我必须自己更改父对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4296019/

相关文章:

c# - 并非所有路径都返回一个值。 - 可选返回?

c# - FileStream: used by another process错误

c# - 我的 'AutoImport' 函数存在错误

c# - 在 LINQ 的 Entity Framework 中传入实体的属性

linq-to-sql - Entity Framework 可以处理来自存储过程的多个结果集(每个来自连接表)吗?

c# - 在哪里可以找到有关在真实项目中使用 Entity Framework 的良好分步教程?

c# - 如何将 Paypal 与 WinForm 桌面应用程序集成

c# - 如何在我的 C# 项目中找到所有静态变量?

c# - 在 Dynamic Linq 中使用 Any() 和 Count()

c# - Linq 没有显示正确的数字