我是Linq to Sql的新手,我面临着访问外国实体的问题。 这是相关的DB:
表MyClass有两列:Id,ProducerId
表人员有两列:Id,Affix
这是我的部分课程:
public partial class MyClass
{
public string ProducerAffix
{
get { return Producer.Affix; }
}
}
生成Producer属性的dbml designer文件与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;
}
}
}
答案 0 :(得分:0)
对于那些可能在以后遇到同样问题的人,我终于找到了它的来源。 当我添加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;
}