I’ve been working on ASP.NET C# with Entity Framework and some people help me very much on certain key points.
There also one point I could not understand fully. Aren’t we supposed to use the object and its subobjects (foreign key relation table data) when we retrieve the data from EF?
Here is my database design (which was also displayed in my previously answered question)

In my code, I simply get Member entity like this:
//In some aspx.cs file
var Mem = new MemberManager().GetById(2);
//In MemberManager class
public Member GetById(long id)
{
using(var Context = new NoxonEntities())
{
return Context.Member.First(c => c.Id == id);
}
}
When I do this:
var Mem = new MemberManager().GetById(2);
var Lang = Mem.Language;
//I get
//Error: 'Mem.Language' threw an exception of type 'System.ObjectDisposedException'
In order to get rid of this exception I needed to do this:
public Member GetById(long id)
{
using(var Context = new NoxonEntities())
{
var Result = Context.Member.First(c => c.Id == id);
//Getting the Language Entity
Result.Language = Context.Language.First(c => c.Id == Result.LanguageId);
return Result;
}
}
Do I have to run a SELECT in order to have FULL entity? What if there were ANOTHER related table to Language table lets say Feature Table. Should I do this:
public Member GetById(long id)
{
using(var Context = new NoxonEntities())
{
var Result = Context.Member.First(c => c.Id == id);
//Getting the Language Entity
Result.Language = Context.Language.First(c => c.Id == Result.LanguageId);
Result.Language.Feature = Context.Language.Feature.First(c => c.Id == Result.FeatureId);
return Result;
}
}
Which could go verrry long and
I’m pretty sure (at least I genuinely hope) I am wrong about something, but if we cannot use the object and its subobjects AFTER selecting, what is the purpose of having EF? Can we only use the subobjects in site the using(var Context = new NoxonEntities()) block?
Thank you,
Think of the context as a database connection. You make this connection available to you when you create the context in the
usingstatement and throw it away at the end of theusing. Everything after theusingblock cannot access the database connection anymore. You get an exception here……because lazy loading tries to load the
Languagenavigation property from the database, but the connection to the database is already disposed. You can use such a lazy loading only within yourusingblock when the connection to the database is still available.You can simplify loading the navigation properties in your example by using eager loading with
Include:Or for both navigation properties use:
It will load the member and the language and feature in one single database query.