2

Is there a way to load an NHibernate entity, with a clause on a child collection? I have a scenario where I log changes in "Operations" i.e. one operation can contain changes to multiple entities. When I want to load the log for a specific entity, I load all Operations with any Changes made to that entity. Loading these Operations cause all changes to be loaded - I only want the relevant changes to be loaded.

Classes:

public class Operation{
   public virtual DateTime TimeStamp { get; set; }
   public virtual IList<Change> Changes { get; private set; }
}

public class Change{
    public virtual string ChangeText { get; set; }
    public virtual int EntityId { get; set; }
} 

Getting the operations for a given entity

 Session.QueryOver<Operation>().Where(o => o.Changes.Any(c => c.EntityId == entityId));
hazard
  • 418
  • 5
  • 10

1 Answers1

0

I. As stated in this Oskar Berggren's answer: https://stackoverflow.com/a/13864061/1679310 you can apply filter 18.1. NHibernate filters

Summary:

Adjust your mapping

<set ...>
    <filter name="myFilter" condition=":myFilterParam = MY_FILTERED_COLUMN"/>
</set>

And then call it this way:

ISession session = ...;
session.EnableFilter("myFilter").SetParameter("myFilterParam", "some-value");
IList results = Session.QueryOver<Operation>()
  .Where(...
  .List();

II. Other option is to filter Changes when quering the Operation: 16.4. Associations

IQueryOver<Operation,Change> query =
 session.QueryOver<Operation>()
   .JoinQueryOver<Change>(o => o.Changes) // added explicit <Change>
     .Where(c => c.EntityId == entityId);
Community
  • 1
  • 1
Radim Köhler
  • 122,561
  • 47
  • 239
  • 335
  • I liked option II, but the "c" in the last Where is the collection of Changes, not each Change item... Looks like it have to something like `Where(cl => cl.Where(c => c.EntityId==entityId))`, however this currently gives me an compilation error.. – hazard Jan 17 '13 at 13:43
  • `session.QueryOver() .JoinQueryOver(o => o.Changes) .Where(c => c.EntityId == entityId);` gives me a compiler error, as c is of type IList, not Change – hazard Jan 17 '13 at 13:59
  • I updated my answer. The JoinQueryOver should be provided with the ``. Now it should be working. More information and details could be found in documentation: http://nhforge.org/doc/nh/en/index.html#queryqueryover-associations – Radim Köhler Jan 17 '13 at 14:15