Thursday, April 21, 2011

NHibernate Error: "Could not initialize proxy - no Session"

If you happen to encounter this kind of error in NHibernate...

Initializing[JqueryAjaxComboBoxAspNetMvcHelperDemo.Models.Category#777]-Could not initialize proxy - no Session.

...even you already have a Fetch clause in your controller code:

public ViewResult Index()
 using (var s = SessionFactoryBuilder.GetSessionFactory().OpenSession())
  return View(s.Query<Product>().Fetch(x => x.Category).ToList());

Worry not much, if your code has a Fetch clause, the problem lies in the data, your data is inconsistent, your table has a foreign key that has no matching primary key in the table it is referring to. Typical of database with no foreign key capability (e.g. MySQL's MyISAM) or with foreign key but not enforced(I'm using Sqlite when I encountered that error)

In our example, there is no primary key 777 in Category table, so we just need to correct our data

You can also encounter the same error(verbatim) even if your data is correct, it happens when you forgot to include the Fetch clause in your query.

Again, NHibernate does a poor job on stating the root cause of error. Another example of vague error from NHibernate, scroll the down to the last portion of the article