Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nhibernate/MVC: Dealing with lazy loaded collections in View

I'm currently using an attribute based approach to nhibernate session management, which means that the session is open for the duration of the Action method, but is closed once control is passed to the View.

This seems like good practice to me, however I'm running in to problems with lazy loaded collections. (This is complicated by the fact that some collections seem to be lazy loading even though they have Not.LazyLoad() set in the fluent mapping).

As I see it, my options are:

  1. Change my ISession management strategy and Keep the session open in the View
  2. Make better use of ViewModels (I'm currently not using them everywhere).
  3. Eager load all of the collections that are causing problems (maybe paged) (fluent problem not withstanding)

1 seems a bit wrong to be - but may be the 'easiest' solution. 2 is probably the proper way to go, but in some cases ViewModels seem slightly redundant, and I'm loathed to introduce more classes just to deal with this issue. 3 seems to be a bit of a dirty fix.

What do you think?

like image 375
UpTheCreek Avatar asked Oct 14 '22 02:10

UpTheCreek


1 Answers

The best way to handle this (in my opinion anyways) is to introduce a service layer in between your UI and your repositories; It should take care of loading everything needed by the view and pass off a flattened (and fully populated) dto to the view.

Often, I go one step further and map the dtos returned from the service layer to view models, which often need to contain data that is very view-specific, and not appropriate for inclusion into the dtos coming from your service layer. Remember, Automapper is your friend when it comes to situations like this.

Using an open-session-in-view pattern is still perfectly acceptable, just don't have your views invoking lazy loading on entity models - this is almost always a horrible idea.

like image 159
DanP Avatar answered Oct 19 '22 01:10

DanP