lkurylo
lkurylo

Reputation: 1641

nhibernate Could not initialize proxy - no Session +asp.net mvc

In action I taken some data from db. Now in view I want to take value from one field which is referenced from other table with lazyload, by I get this error: Could not initialize proxy - no Session

I wonder what I can do now.

public ActionResult Index()
        {
            using (NHUnitOfWork.Start())
            {
                var news = articlesRepository.News(0, 20);
                return View(news);
            }
        }

<%= Html.ActionLink(Html.Encode(Model.Author.Login), "zyx", "xyz") %>

 public ArticleMap()
        {
            References(x => x.Author).Not.Nullable().LazyLoad().Column("Author").Cascade.SaveUpdate();
         //...
        }

    public class Article : EntityBase<int>
    {
        public virtual User Author { get; set; }
         //...
    }

Upvotes: 1

Views: 2645

Answers (1)

Paco
Paco

Reputation: 8381

You can only access the database when the session is open. You can do three things:

  1. Keep the session open until the webrequest is finished
  2. Eager load the author
  3. Load the author in the controller instead of in the view.

Upvotes: 3

Related Questions