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 entit开发者_开发知识库y
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:
var subCriteria = DetachedCriteria.For<Room>(); // subquery
subCriteria.Add(Expression.Eq("House", house)); // where clause in subquery
subCriteria.SetProjection(Projections.Id()); // DetachedCriteria needs to have a projection, id of Room is projected here
var criteria = session.CreateCriteria<Person>();
criteria.Add(Subqueries.PropertyIn("Room", subCriteria)); // in operator to search in detached criteria
var result = criteria.List<Person>();
This produces something like this:
SELECT this_.Id as Id4_0_, this_.Name as Name4_0_, this_.RoomId as RoomId4_0_
FROM [Person] this_
WHERE this_.RoomId in (SELECT this_0_.Id as y0_ FROM [Room] this_0_ WHERE this_0_.HouseId = @p0)',N'@p0 int',@p0=1
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:
var query = session.Query<Person>().Where(x => x.Room.House == house);
var linqResult = query.ToList<Person>();
which produces different SQL query but result set is the same:
select person0_.Id as Id4_, person0_.Name as Name4_, person0_.Room_id as Room3_4_
from [Person] person0_, [Room] room1_
where person0_.Room_id=room1_.Id and room1_.House_id=2
精彩评论