【问题标题】:ObjectDisposedException on Foreign entity外部实体上的 ObjectDisposedException
【发布时间】:2015-02-19 18:13:33
【问题描述】:

我是 Linq to Sql 的新手,我遇到了有关访问外部实体的问题。 这是相关的数据库:

  • 具有两列的 MyClass 表:Id、ProducerId

  • Table Person 有两列:Id、Affix

这是我的部分课程:

public partial class MyClass
{
    public string ProducerAffix
    {
        get { return Producer.Affix; }
    }
}

以及生成Producer属性的dbml设计器文件与ProducerId外键相关:

[global::System.Data.Linq.Mapping.AssociationAttribute(Name="Person_MyClass1", Storage="_Person1", ThisKey="ProducerId", OtherKey="Id", IsForeignKey=true)]
    public Person Producer
    {
        get
        {
            return this._Person1.Entity;
        }
        set
        {
            Person previousValue = this._Person1.Entity;
            if (((previousValue != value) 
                        || (this._Person1.HasLoadedOrAssignedValue == false)))
            {
                this.SendPropertyChanging();
                if ((previousValue != null))
                {
                    this._Person1.Entity = null;
                    previousValue.MyClass.Remove(this);
                }
                this._Person1.Entity = value;
                if ((value != null))
                {
                    value.MyClass.Add(this);
                    this.ProducerId = value.Id;
                }
                else
                {
                    this.ProducerId = default(System.Guid);
                }
                this.SendPropertyChanged("Producer");
            }
        }
    }

访问 MyClass 的 Affix 属性时,会抛出 ObjectDisposedException... 访问属性时需要打开 Datacontext 吗?

我阅读了这篇文章LINQ to SQL ObjectDisposedException on entity that never asked for,但真的很想避免创建 ViewModel... 还有其他解决办法吗?

非常感谢!

编辑

按照 JAT 的回答,我尝试使用 DLO,但真的不知道如何从中返回我的外部值...我找到了这个教程 (http://www.codeproject.com/Articles/37857/Optimizing-LINQ-Queries-using-DataLoadOptions),然后我必须写一个查询吗?

public string Affix
    {
        get
        {
            using (var db = new DBDataContext())
            {
                var dlo = new DataLoadOptions();
                dlo.LoadWith<Person>(p => p.Affix);
                db.LoadOptions = dlo;
                ...
                return Producer.Affix;
            }
        }
    }

【问题讨论】:

标签: c# linq-to-sql objectdisposedexception


【解决方案1】:

对于那些以后可能会遇到同样问题的人,我终于知道这是从哪里来的。 当我添加我的 Person 和 MyClass 时,我使用了这个函数:

public static Person Add(Person person)
{
    using (var db = new DBDataContext())
    {
        db.Person.InsertOnSubmit(person);
        db.SubmitChanges();
        return person;
    }
}

删除“使用”对我有用,现在我可以访问我的外键实体。 我真的不明白为什么,因为我读到“使用”是一个比“新”更好的解决方案,因为关闭问题,但似乎它不能正常工作,所以我删除了它。

public static Person Add(Person person)
{
    var db = new DBDataContext();

    db.Person.InsertOnSubmit(person);
    db.SubmitChanges();
    return person;

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-12
    • 1970-01-01
    • 2019-05-11
    • 1970-01-01
    • 2020-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多