Get your entity rather than the proxy

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);
Advertisements
Explore posts in the same categories: nhibernate

Tags:

You can comment below, or link to this permanent URL from your own site.

2 Comments on “Get your entity rather than the proxy”

  1. ivowiblo Says:

    The problem is your design. You should never take a decision based on the inheritance. Instead you could use the polymorphism itself to handle that. For example, using a double dispatch or a visitor pattern.

    Also, taking an entity using a query will avoid first and second level cache.

  2. Nieve Says:

    Ivowiblo-
    Many many thanks for that 🙂 You’re absolutely 100% right saying that- one should never take a decision based on the inheritance/type of subclass. And this is a much more important reminder than my actual post…


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: