MVC2.NET pass object from viewmodel to view and ac

2019-08-26 22:28发布

问题:

When working with Viewmodels from linq to sql I have an architectural problem.

When you have an object from your db (let's say "person"), and you load it in your viewmodel. After this in your view, when you try to acces referenced classes (let's say a person has children object which is a different table in db, and a different datacontext object). You get a "cannot access disposed datacontext object (or something) which is logical, because you loaded your object and disposed the datacontext. for example:

"object" ->foreach(Child child in Model.Person.Children.ToList()){}

But how can you make it so that you can ("preload"?) the children or acces them without having to create a new datacontext, and reload the person in your View ?

回答1:

Use DataLoadOptions.LoadWith()

See examples here: http://msdn.microsoft.com/en-us/library/Bb386917(v=VS.90).aspx

You must specify DataLoadOptions and assign in to the DataContext instance before executing any queries.