views:

42

answers:

1

I need to modify the query used to load many-to-one references in my model.

It needs to work with lazily loaded entities as well.

Specifically, I need to be able to further filter this data. Unfortunately, NH will not allow me to filter many-to-one relationships using the built in filtering system (?). I could just be doing something incorrect.

Is there a hook where I can manually and dynamically modify the query used to load the data? Or an alternative to filters that will allow me to specify parameters?

Background:

I am working with a database that is using a form of revision control, with each entity having a natural ID PK, an EntityId, a RevisionValidTo and RevisionValidFrom field. There may be many rows using the same EntityId, which is the reference for other tables to join on, but the Revision ranges are mutually exclusive. Thus, the relationship is only many-to-one IIF the filter is applied. However, NH offers no way to specify a filter on many-to-one references (they do for collections...)

+1  A: 

I've been down this same road before I had the revelation that I don't have to lazy load my child objects. It may be worth the savings to just fill the entity from the repository when it is initially loaded. If you don't want to take the hit every time, you could put a little fluency on whatever you have interacting with the repository

GetObject(entityId).Including(x => x.Revisions).Between(...)
Corey Coogan
If I don't restrict the results that NHibernate gets when it executes the query, it gets multiple rows back from the DB when it expects one. It throws an exception. I can't really populate my child objects manually.
snicker
You would be able to control that with criteria you pass in as you manually populate it. I've posted questions like this before, one last week in fact, and they never get answered. After spending days on trying to get it to work how I thought it should, I conceded to get it to work how I thought it could. In the end, I got the behavior I needed and I don't think I'm suffering any performance since the same ISession is used.
Corey Coogan
@Corey: Could you elaborate a little more in your answer? I am still confused how I could load entity Foo with a reference to entity Bar and have it maintain the criteria without manually writing the query for each of my entities (and there are *many*). I don't have this problem just once, I have it on every single entity in my model. I'm sure this is simple, I just need to wrap my head around it. Some more code would be helpful ;)
snicker