0

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

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

  • 具有两列的表人: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 ?

我在从未要求但真的想避免创建 ViewModel的实体上阅读了这篇文章LINQ to SQL ObjectDisposedException ......还有其他解决方案吗?

非常感谢 !

编辑

按照 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;
            }
        }
    }
4

1 回答 1

0

For those who might face the same issue later, I finally found out where this came from. When I added my Person and my MyClass, I used this function :

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

Removing the "using" did the trick for me and now I can access my foreign keys' entities. I sincerely don't understand why because I read that "using" was a better solution than "new" because of the close issue, but seems like it does not work correctly with it, so I removed it.

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

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

}
于 2015-02-27T16:00:38.960 回答