Don't load all relationships

I have a simple database from which I create Linq2SQL classes using datacontext. In one part of my application, I would like to load all the relationships in order to get the children. In another part of the application, I pass this relationship across the border between the model and the view, and I would not want to miss all of this, since the set of children is quite large. Is there a way for these child classes to be exported to one section and exported to another?

I know that the child property for False is specified in the datacontext, but this is a global change.

+2


source to share


2 answers


You can do this using the DataLoadOptions parameter in the data context. You will probably have some kind of builder class somewhere in your application. For the quickest and dirtiest solution, you can 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;
    }
}

      

+1


source


One solution is to pass the relation as IQuerable. This will ensure that the relationship is not executed until needed. If you obsess over the relationship, then it will be fulfilled for every child.



Another method could be using DTO objects to create the ViewModel you want to pass. This means that your ViewModel can be very similar to the interface.

0


source







All Articles