0

I am trying to use NHibernate in my project, i am getting the following error "Initializing[BO.Job#34543]-failed to lazily initialize a collection of role: BO.Job.bInterview, no session or session was closed". can someone help me.

public HttpResponseMessage GetbyId(int Id)
        {
            Job job = new Job();
            try
            {
                using (ISession session = NHibernateSession.OpenSession())  // Open a session to conect to the database
                {
                    // books = session.Query<Book>().ToList(); //  Querying to get all the jobs
                    JobRepo = new Repo<Job>(session);
                    job = JobRepo.GetById(Id, "Job_selectbyId");
                }
                return Request.CreateResponse(HttpStatusCode.OK, job);

            }
            catch (Exception exp)
            {
                Log.Error(exp);
                return Request.CreateResponse(HttpStatusCode.ExpectationFailed, job);
            }
        }

public T GetById(int id,string SPName)
        {
            T result;
            //return await Task.Run(() =>
            //{
                IQuery query = _session.GetNamedQuery(SPName);
                query.SetParameter("job_id", id);
                //book = _session.Query<Book>().Where(b => b.Id == id).FirstOrDefault();
                result = query.UniqueResult<T>();
                return result;
            //});
        }

1 Answer 1

1

This is probably because you're trying to access a property that's been marked as 'lazy' after the session has been closed.

My guess is that you're returning job and then the session is being disposed. Some other code is then attempting to access the Interview property of the returned job, which needs to session to implement the lazy loading feature but the session's been disposed.

You can change you query so that Interview is 'pre-fetched' or you can change your mapping so that there's no lazy initialisation on the class or the property.

Sign up to request clarification or add additional context in comments.

2 Comments

job is having foreign key relation with interview table.I tried removing "Lazy" Property in both the hbm.xml files, but still same problem.
Maybe the mapping cannot influence hydration of the object graph because your query source is a stored proc? To help diagnosing this problem, you could force the Interview to be loaded by accessing the property before you return job: job.Interview.SomethingHarmless();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.