views:

134

answers:

2

I have recently started using custom ViewModels (For example, CustomerViewModel)

public class CustomerViewModel
{
    public IList<Customer> Customers{ get; set; }

    public int ProductId{ get; set; }

     public CustomerViewModel(IList<Customer> customers, int productId)
     {
        this.Customers= customers;
        this.ProductId= productId;
     }

     public CustomerViewModel()
     {
     }
 }

... and am now passing them to my view instead of the collections themselves (for example, var Custs = repository.getAllCusts(id) ) as it seems good practice to do so.

The problem i have encountered is that when using ViewModels; by the time it has got to the the view i have lost the ability to lazy load on customers. I do not believe this was the case before using them.

Is it possible to retain the ability of Lazy Loading while still using ViewModels? Or do i have to eager load using this method?

Thanks, Kohan.

+1  A: 

Technically, yes, it's possible to expose the lazy loaded collection on the viewmodel via an IEnumerable<> property. Just expose the getter and have the getter perform the Linq-to-sql query.

I've not had much success with it myself, though, because I prefer to expose collections on viewmodels via a ReadOnlyObservableCollection<>. Using that collection directly must load the data eagerly. I can imagine creating a collection like the ReadOnlyObservableCollection<> that cheats and only does an eager load if the user calls something that requires it (e.g., indexing into the collection), but I've never cared enough to actually implement such a thing.

Greg D
+2  A: 

I imagine that what's stopping your L2S Customer from lazy loading it's properties is that your DataContext is disposed by your repository.

One solution is to not dispose your DataContexts until the request has been dealt with - there's quite a few patterns on the internet for dealing with this.

Another option is to not use lazy loading. Since you've got a collection of customers, I'd say that it would be a really good idea to eagerly load whatever it is you need, otherwise you'll be hitting the database once per customer

Rob Fonseca-Ensor