The data structure is as follows:
A house has many rooms. Each room has many persons.
What I want to do is to get all persons for a house. In plain SQL I would write the following:
SELECT * FROM Person WHERE Room_id
IN
(SELECT Id FROM Room WHERE House_id = 1)
How can I write that in Fluent NHibernate’ish code?
For this example, we can assume that the entities and mappings look like this:
House entity
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual IEnumerable<Room> Rooms { get; set; }
House mapping
Id(x => x.Id);
Map(x => x.Name);
HasMany(x => x.Rooms);
Room entity
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual House House { get; set; }
public virtual IEnumerable<Person> Persons { get; set; }
Room mapping
Id(x => x.Id);
Map(x => x.Name);
References(x => x.House);
HasMany(x => x.Persons);
Person entity
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual Room Room { get; set; }
Person mapping
Id(x => x.Id);
Map(x => x.Name);
References(x => x.Room);
To get SQL query close to yours you can use these criterias:
This produces something like this:
I tested it in FNH1.2 and NH3.1 but it should work well in NH2.1 as well.
EDIT:
UpTheCreek is right. Linq is more clear than Criteria API. For example:
which produces different SQL query but result set is the same: