我有以下查询可以得到我想要的结果:
int associatedId = 123;
MyObject alias = null;
var subQuery = QueryOver.Of<DatabaseView>()
.Where(view => view.AssociatedId == associatedId)
.And(view => view.ObjectId == alias.ObjectId)
.Select(view => view.ObjectId);
var results = session.QueryOver<MyObject>(() => alias)
.WithSubquery.WhereExists(subQuery)
.List();
DatabaseView
已被映射为实际的 NHibernate 实体(因此我可以将它与 QueryOver
一起使用),但它不与 MyObject
关联。在 HBM 映射中。
此查询返回 IList<MyObject>
使用SELECT ... FROM MyObject WHERE EXISTS (subquery for DatabaseView here)
。我如何重写它以返回相同的数据但使用 JOIN 而不是子查询?
请您参考如下方法:
在 NHibernate 5.1+ 中,可以通过 Entity Join 进行 QueryOver/Criteria :
int associatedId = 123;
MyObject alias = null;
DatabaseView viewAlias = null;
var results = session.QueryOver<MyObject>(() => alias)
.JoinEntityAlias(() => viewAlias, () => viewAlias.ObjectId == alias.ObjectId && viewAlias.AssociatedId == associatedId)
.List();
标准示例:
int associatedId = 123;
var results = session.CreateCriteria<MyObject>("alias")
.CreateEntityAlias(
"viewAlias",
Restrictions.EqProperty("viewAlias.ObjectId", "alias.ObjectId")
&& Restrictions.Eq("viewAlias.AssociationId", associatedId),
JoinType.InnerJoin,
typeof(DatabaseView).FullName)
.List();