Fluent NHibernate:如何将此查询编写为条件?
数据结构如下: 一座房子有很多房间。每个房间都有很多人。
我想做的就是让所有人都买房子。在普通 SQL 中,我会编写以下内容:
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?
对于此示例,我们可以假设实体和映射如下所示:
House 实体
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual IEnumerable<Room> Rooms { get; set; }
House 映射
Id(x => x.Id);
Map(x => x.Name);
HasMany(x => x.Rooms);
Room 实体
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 映射
Id(x => x.Id);
Map(x => x.Name);
References(x => x.House);
HasMany(x => x.Persons);
Person 实体
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual Room Room { get; set; }
Person 映射
Id(x => x.Id);
Map(x => x.Name);
References(x => x.Room);
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);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
要获得接近您的 SQL 查询,您可以使用以下条件:
这会产生类似这样的结果:
我在 FNH1.2 和 NH3.1 中测试了它,但它在 NH2.1 中也应该运行良好。
编辑:
UpTheCreek 是对的。 Linq 比 Criteria API 更清晰。例如:
产生不同的 SQL 查询,但结果集相同:
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: