我有这个对象图:
// Lots of stuff omitted for brevity; these are all virtual properties and there
// are other properties which aren't shown on all classes.
class A {
B b;
C c;
DateTime timestamp;
}
class B {
X x;
Y y;
}
class X {
int id;
}
class C { }
class Y { }
or to put it more simply,
a = {
b: {
x { id: int },
y: { }
},
c: { },
timestamp: DateTime
}
现在我正在查询我将返回一个A
s 列表并且我需要它们的所有B
s、C
s、X
s 和Y
s。我还将按 B 将它们分组到查找中。
ILookup<B, A> GetData(List<int> ids) {
using (ISession session = OpenSession()) {
var query = from a in session.Query<A>()
where ids.Contains(a.b.x.id)
orderby A.timestamp descending
select a;
query = query
.Fetch(a => a.b)
.ThenFetch(b => b.x)
.Fetch(a => a.b)
.ThenFetch(b => b.y)
.Fetch(a => a.c);
return query.ToLookup(a => a.b);
}
}
需要注意的几点:
- 这是一个需要返回所有数据的报告 - 无限的结果不是问题。
- 我正在通过 using 进行分组,
ToLookup
因为group by
当您需要所有实际值时 using 似乎更复杂 - 您需要查询数据库中的组,然后查询它们的实际值。
我的问题是如何正确指定获取策略。我这样做的方式是我发现它运行的唯一方式(已获取所有 bx 和值) - 但它产生的 SQL 似乎是错误的:
select /* snipped - every mapped field from a0, b1, x2, b3, y4, c5 - but not b6 */
from [A] a0
left outer join [B] b1
on a0.B_id = b1.BId
left outer join [X] x2
on b1.X_id = x2.XId
left outer join [B] b3
on a0.B_id = b3.BId
left outer join [Y] y4
on b3.Y_id = y4.YId
left outer join [C] c5
on a0.C_id = c5.CId,
[B] b6
where a0.B_id = b6.BId
and (b6.X_id in (1, 2, 3, 4, 5))
order by a0.timestamp desc
正如您所看到的,它获得了a.b
3 次的值 -b1
以及b3
获取和b6
where 子句。
- 我认为这对数据库性能有负面影响——我说得对吗?
- 有没有办法修改我的
.Fetch
调用,使其只获取a.b
一次? - 这是解决我的问题的好方法吗?