I'm quite a newbie with Linq to Sql, and I'm facing an issue regarding accessing a foreign entity. Here is the related DB :
Table MyClass with two columns : Id, ProducerId
Table Person with two columns : Id, Affix
Here is my partial class :
public partial class MyClass
{
public string ProducerAffix
{
get { return Producer.Affix; }
}
}
And the dbml designer file where the Producer property is generated related to ProducerId foreign key :
[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");
}
}
}
When accessing MyClass' Affix property, an ObjectDisposedException is thrown... Do I need to open a Datacontext when accessing the property ?
I read this post LINQ to SQL ObjectDisposedException on entity that never asked for but really would like avoiding creating a ViewModel... Is there any other solution ?
Thanks a lot !
EDIT
Following JAT's answer I tried to use the DLO but don't really know how to return my foreign value from it... I found this tutorial (http://www.codeproject.com/Articles/37857/Optimizing-LINQ-Queries-using-DataLoadOptions), do I have to write a query then ?
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;
}
}
}
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;
}