Michael Niemand
Michael Niemand

Reputation: 1754

lazy loaded NHibernate collections into ViewModels?

I have my NHibernate mappings set to lazy loading = true. In my CustomersViewModel I have something like:

        foreach (Customer c in _customerRepository)
        {
            this.Customers.Add(new SingleCustomerViewModel(c));
        }

This obviously kills all the lazy loading, since the customers are passed one by one.

How do I get my collections (including subcollections and sub-subcollections a.s.f.) of model-objects into the corresponding ObservableCollections of my ViewModels to bind to the UI?

This seems to be a common problem, but I found no answer, neither here nor on the Googles ...

Upvotes: 1

Views: 235

Answers (2)

Matt Enright
Matt Enright

Reputation: 7484

This is a classic "SELECT N+1" problem: whichever query layer you are using for NHibernate offers you a way to eagerly load the child collections in your initial query to avoid this row-by-row query pattern.

With the LINQ provider, for example:

session.Query<Customer> ()
        .FetchMany (c => c.Widgets) // eagerly load child collections
        .ThenFetchMany (w => w.Frobbers); // now get grandchild collection

If you're using HQL, just add the fetch keyword to your joins.

Upvotes: 0

Surya
Surya

Reputation: 4992

I am not sure I completely understand the question . But I was thinking why not change your getCustomers method to

 IEnumerable<SingleCustomerViewModel> getCustomers(){
     return  from c in _customerRepository select SingleCustomerViewModel(c);
  }

Since LINQ expressions are lazily evaluated you nhibernate collection wont be initialized until its actually bound to the UI .

Upvotes: 3

Related Questions