我是 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;
}
}
}