建议#1
在执行查询以获取所需数据后,您可以进行一些 LINQ 操作。
var result = Session.QueryOver<Entity>()
.Where(e => e.Id == entityId) // Filter,
.Fetch(e => e.ReferenceEntity).Eager // join the desired data into the query,
.List() // execute database query,
.Select(e => e.ReferenceEntity) // then grab the desired data in-memory with LINQ.
.SingleOrDefault();
Console.WriteLine("Name = " + result.Name);
这很简单,可以完成工作。
在我的测试中,它产生了一个查询。这是输出:
SELECT
this_.Id as Id0_1_, this_.Name as Name0_1_, this_.ReferenceEntity_id as Referenc3_0_1_,
q5379349_r2_.Id as Id1_0_, q5379349_r2_.Name as Name1_0_
FROM
[Entity] this_
left outer join [ReferenceEntity] q5379349_r2_
on this_.ReferenceEntity_id=q5379349_r2_.Id
WHERE this_.Id = @p0;
建议#2
另一种方法是使用 EXISTS 子查询,它会稍微复杂一些,但会在第一次返回正确的结果而无需任何后数据库操作:
ReferenceEntity alias = null;
var result = Session.QueryOver(() => alias)
.WithSubquery.WhereExists(QueryOver.Of<Entity>()
.Where(e => e.Id == entityId) // Filtered,
.Where(e => e.ReferenceEntity.Id == alias.Id) // correlated,
.Select(e => e.Id)) // and projected (EXISTS requires a projection).
.SingleOrDefault();
Console.WriteLine("Name = " + result.Name);
经过测试 - 导致单个查询:
SELECT this_.Id as Id1_0_, this_.Name as Name1_0_
FROM [ReferenceEntity] this_
WHERE exists (
SELECT this_0_.Id as y0_
FROM [Entity] this_0_
WHERE this_0_.Id = @p0 and this_0_.ReferenceEntity_id = this_.Id);