BobRock
BobRock

Reputation: 3467

Nhibernate lazy loading error on session.Get

I'm receiving on my controller some int which is parameter I'm using for getting entity. This entity have List Collection which I need to load together with my entity. I cannot access Fetch method in session.Get so I dont know how to achive. When in my view I tried to access to my collection like entity.Collection it throws an error, no session or session was closed

Here is my code

public ActionResult Details(int id)
{
   MyDomain.Property data = null;
   using (//open session)
   {
      using (//using transaction)
      {
          data = session.Get<MyDomain.Property>(id);                    
          //I need to load Photo() collection. 
          transaction.Commit();
      }
   }
   return PartialView("DetailsPartial", data);        
}

Upvotes: 0

Views: 310

Answers (1)

Anton
Anton

Reputation: 1583

Your entity has a collection's property with a proxy (not real collection). When you close session you can't use lazy load, so, you need to get real collection objects. You should get it with query:

Session.QueryOver<Entity>()
 .Where(entity => entity.Id == id)
 .Fetch(entity => entity.CollectionProperty).Eager
.SingleOrDefault<Entity>();

Upvotes: 1

Related Questions