【发布时间】: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;
}
}
}
【问题讨论】:
-
如果你想在上下文被释放后访问相关实体,你可以使用DataLoadOptions
-
非常感谢您的回答,我编辑了我的第一篇文章!
标签: c# linq-to-sql objectdisposedexception