Hello everybody.
I'm struggling with the ADO.NET Entity Framework. This is my ER-diagram:
--------------------- ----------------- ---------------
| GrandParentEntity |<-------| ParentEntity |<-------| ChildEntity |
+-------------------+ 1 N +---------------+ 1 N +-------------+
| Id | | Id | | Id |
--------------------- | GrandParentFk | | ParentFk |
----------------- ---------------
Have a question about the lifetime of an object context. Assume that i requests my data as follows:
public static List<MyParentEntity> GetMyParentEntity()
{
using (var context = new MyObjectContext(blablabla...))
{
var resultSet = from e in context.MyParentEntitySet select e;
return resultSet.ToList();
}
}
I get a list of all my parent entities. Some time later (hours?), the user decides which one he would like to inspect. (Meanwhile, the entity object passed through several tiers of the application.) I now have to load all the details of the record:
public static void LoadChildren(MyParentEntity pEntity)
{
using (var context = new MyObjectContext(blablabla...))
{
pEntity.GranParentEntityReference.Load();
pEntity.ChildEntites.Load();
}
}
This leads to an ObjectDisposedException, because the MyParentEntity object has lost its connection to the object context that created it. I have several possibilities to handle this:
1) I can use one and the same instance of MyObjectContext all the time and never close it. This leads to a huge waste of memory.
2) I can Detach() manually each and every single entity object (and its child and parent entities) every time I leave the "using (context)" block. And I can Attach() them every time i enter a new "using(context)" block. Leads to a lot of effort. (I my opinion a framework should reduce the effort instead of increase it.)
3) Reload and then throw away each entity every time I enter a new "using(context)" block. Leads to more (unnecessary) load on the SQL Server and also wastes memory.
4) I can load all details and all references and all references of all references and the references of those references when the application starts. (No discussion, this really is silly!)
5) ... (Did I forget an option?)
Now the big QUESTION for you: which way should i choose? Is there another way that i didn't see? Or did i misunderstand the spirit of the framework entirely?
Thanks in advance
UPDATE: It is a Windows Forms Application.