My Resume

  • My Resume (MS Word) My Resume (PDF)


  • Microsoft Most Valuable Professional
  • INETA Community Champion
  • Leader, NJDOTNET: Central New Jersey .NET User Group

Sunday, April 13, 2008

NHibernate Lazy Loading Snafu

Oh, man did I get thrown for a loop last night... 

I've got a test project I'm working on that uses NHibernate.  In this project, I've got a Building class, which has an Address attribute, of type Address, for which I overrode the ToString() method like so:


I've also got a page that grabs a bunch of Buildings from the NHibernate session and binds them to a Repeater.  For my initial tests, just to see if everything worked, I just bound right to the Address property on the Building in my markup and everything worked fine.  That is, the address printed out just as it was supposed to - in just the right format I'd set in the ToString() overload.  Then I went to refactor the page and break the address out into it's individual bits to show them in a slightly different way...  and was greeted with a null reference exception!

I was troubleshooting for a good half hour or so before I came across this dialog:


WTF!?  How in the world could my ToString() overload be generated correctly when all of its properties are null!?  And then I realized - lazy loading!  D'oh!  I went to my NHibernate mapping file for the Building class and updated it, adding the "lazy='false'" attribute, so it ended up looking like so:


and now everything works like a charm!  This fix doesn't really bother me because the Address probably shouldn't have been lazily loaded to begin with, but I never did end up figuring out how exactly that AddressProxy was able to give info to my ToString() override but was not nice enough to populate my properties for me!  Looks like I've got to learn about lazy loading and NHibernate Proxy classes!

If you've got some ideas on how this happened, please leave a comment - I'd love to know!  But for now, I'm just happy I figured it out!