Linq to NHibernate ThenFetch多个属性
我有这个对象图:
// 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);
}
}
有几点需要注意:
这是一份需要返回所有数据的报告 - 无限结果不是问题。
我正在使用ѭ7进行分组,因为当你需要所有实际值时,使用group by
似乎更复杂 - 你需要查询数据库中的组,然后查询它们的实际值。
我的问题是如何正确指定提取策略。我完成它的方式是我发现运行的唯一方法(已经获取了所有的b.x和b.y值) - 但它产生的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
?
这是解决我问题的好方法吗?
没有找到相关结果
已邀请:
1 个回复
死搭胯
你可以做一个进一步的优化,使用ToFuture()方法而不是ToList()......我不确定它如何与LINQ和ToLookup方法一起工作,但它不应该太难以正确。 ToFuture()将对查询进行排队并立即执行所有查询,而不是为每个查询执行单独的数据库连接。