Keeping Linq in SQL when using ViewModels (ASP.NET MVC)
I recently started using custom ViewModels (like 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 now I pass them to my view instead of the collections themselves (e.g. var Custs = repository.getAllCusts (id)) as seems like good practice.
The problem I am facing is that when using ViewModels; by the time it hit the point, I had lost the ability to lazily load clients. I don't think this was the case before using them.
Is it possible to preserve the Lazy Loading ability while using ViewModels? Or do I need to eagerly download this method?
Thank you, Cohan.
a source to share
My guess is that what stops your L2S client from lazily loading its properties is that your DataContext is being hosted in your repository.
One solution is not to delete your DataContexts until after the request has been processed - there are quite a few templates out there on the web to work with this.
Another option is not to use lazy loading. Since you have a collection of clients, I would say it would be a really good idea to eagerly load whatever you need, otherwise you will be hitting the database once per client
a source to share
Technically, yes, you can represent a lazy loaded collection on the viewmodel using a property IEnumerable<>
. Just expose the getter and ask the getter to run a Linq-to-sql query.
I haven't had much success with this though, because I prefer to expose collections on viewmodels via ReadOnlyObservableCollection<>
. Using this collection directly should load data eagerly. I can imagine how to create a collection of type ReadOnlyObservableCollection<>
that cheats and only loads if the user calls something that requires it (like indexing into a collection), but I never really cared about actually implementing such a thing.
a source to share