c# - Fluent NHibernate - 'failed to lazily initialize a collection' - Querying Over a Collection -


i have self-referential model class:

public class word {     public virtual int id { get; set; }     public virtual string text { get; set; }     public virtual ilist<word> synonyms { get; set; }     public virtual int { get; set; } } 

i trying query synonyms of word 1 , returning list of words in json format in mvc 3 app:

[httppost] public jsonresult synonyms(string wordtext) {     using (var session = ...)     {         using (var tx = session.begintransaction())         {             var word = session.queryover<word>()                               .where(w => w.text == wordtext)                               .singleordefault();              var results = new synonymsresults()             {                 words = word.synonyms                             .where(x => x.extra == 1)                             .select(x => x.text)             };              return json(results);         }      } } 

i'm getting error fails lazily initialize collection. i'm not sure why though, since still in same session here , using transaction.

the result executes later, after action has finished running , outside of session. fact have returned json(results) doesn't mean these results serialized json. action first finish executing, asp.net mvc pipeline handle execution result (onresultexecuting) , @ point javascriptserializer touch collection. @ point of time sessions , transactions long gone.

so either instruct orm eagerly fetch dependent collections or better take @ following series of blog posts , use view models.


Comments