views:

28

answers:

2

I have a simple database from which I am generating Linq2SQL classes using a datacontext. In one part of my application I would like to load the entire relationship such that I get child records. In another part of the application I am passing that relation across the boundary between model and view and I would like to not pass the entire thing since the set of children is pretty large. Is there a way to not have these child classes exported in one section and be exported in another?

I am aware of setting the child property to False in the datacontext but that is a global change.

+1  A: 

You can do it with the DataLoadOptions setting on the data context. You'll probably have some sort of builder class somewhere in your application. For the quickest and dirtiest solution, you could do something like the following...

public class SqlContextBuilder
{
    public SqlContextBuilder(MyDataContext dataContext)
    {
        _dataContext = dataContext;
    }
    private readonly MyDataContext _dataContext;
    public MyDataContext CreateEagerLoadingContext()
    {
        var options = new DataLoadOptions();
        // set those options!
        _dataContext.LoadOptions = options;
        return _dataContext;
    }
    public MyDataContext CreateLazyLoadingContext()
    {
        // lazy loading happens by default
        return _dataContext;
    }
}
Jarrett Meyer
That doesn't prevent the loading of data, it simply delays it until it is requested. As I'm passing a collection of data back to the view it is requested and filled in.
stimms
The ORM is going to have the binding (provided you use the same DBML). If you never request them, the child classes will never be filled. Therefore, you have one fetch opportunity where the child classes are filled on the initial query, and another where they are lazy loaded (or perhaps never loaded at all).
Jarrett Meyer
A: 

One of the solutions is to pass the relation as IQuerable. This will make sure that the relation is not executed until is it required. If you loop over the relation then it will be executed for each child.

Another technique might be to use DTO objects to create a ViewModel of which you like to pass. This means your ViewModel might be very similar to the interface.

azamsharp