views:

606

answers:

2

How do I access a lazy loaded property of an ActiveRecord model from within the view?

I have a news model that Belongs to a Category Model, both of which are marked as Lazy=true

I'm able to access a lazy loaded property in my view by doing the following in my controller

using (new SessionScope())
{
    results = _service.FindAllNews(start, pageSize, new[] { Order.Asc("Id") });
    foreach (var result in results)
    {
        var category = result.Category;
    }
}
return View(results);

Then in my view, I parse through the results and display the category title with the following

<%= Html.Encode(item.Category.Title) %>

Obviously if I don't reference the property in my controller, I will get a session scope error when trying to call the property in the view.

But this seems wrong to me. Is there a better way of initializing the lazy loaded properties of a model before reaching the view? I suppose I could write an Init function in the model, but that also seems wonky as well.

+2  A: 

I turned to the AR google group and found the answer I was looking for. I thought I would share it with everyone here in case someone else is looking for the same thing.

To change where the session scopes are created and destroyed for lazy loading with ActiveRecord, you should add the following to your web.config.

<system.web>
    <httpModules>
        <add 
            name="ar.sessionscope" 
            type="Castle.ActiveRecord.Framework.SessionScopeWebModule, Castle.ActiveRecord" />
    </httpModules>
</system.web>

This changes where the session scope is created and disposed to match the session scope per request here http://www.castleproject.org/activerecord/documentation/trunk/usersguide/web.html.

kayluhb
+3  A: 

The simple solution is: Don't perform Lazy loading within your view. The View in MVC by definition has no business loading anything.

It's up to the controller to do that so you can test this behavior.

And yes, you don't need to set that in your mappings. You can query your objects with another Fetchmode so they get eagerly loaded in that one particular case.

Tigraine
While the marked answer is directly what the user was asking, this is a better answer. The View shouldn't do anything that touches the DB.
consultutah