开发者

lazy loaded NHibernate collections into ViewModels?

I have my NHibernate mappings set to lazy loading = true. In my CustomersViewModel I have something lik开发者_如何转开发e:

        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 ...


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 .


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜