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