Snowing Code

Personal notes on software development


Get your entity rather than the proxy

(Publish date: 02/02/2010)

A small problem we’ve encountered today- this is truly basics, but you can never know, this might serve me or someone at some point. One of my colleagues was trying to figure out why was his UserRepository.Get(id) method was returning him a proxy rather than a proper User. He was trying to determine what sort of user is it after getting it to know what should he display, and since a proxy was returned, none of the conditions were met (we have other sub-user classes and tables derived from the User class).
It turned out that he was calling during the same lifespan of his session another method that gets another entity which references his User (say Demand.User) and since by default NH gets us a proxy, the session returned to him what it had in his cache.
What we did was quite simply add the method DemandRepository.GetDemandWithUser(id), eagerly fetching the User property, which looks in NHibernate.Linq (old version- 1.1 as far as I remember) like that:

 return Session<Demand>().Expand("User").SingleOrDefault(d=>d.id == demandId);
Tags: nhibernate
blog comments powered by Disqus