LINQ自引用查询
我有以下SQL查询:LINQ自引用查询,linq,linq-to-nhibernate,Linq,Linq To Nhibernate,我有以下SQL查询: select p1.[id], p1.[useraccountid], p1.[subject], p1.[message], p1.[views], p1.[parentid], max( case when p2.[created] is null then p1.[created] else p2.[created] en
select
p1.[id],
p1.[useraccountid],
p1.[subject],
p1.[message],
p1.[views],
p1.[parentid],
max(
case
when p2.[created] is null then p1.[created]
else p2.[created]
end
) as LastUpdate
from forumposts p1
left join
(
select
id, parentid, created
from
forumposts
) p2 on p2.parentid = p1.id
where
p1.[parentid] is null
group by
p1.[id],
p1.[useraccountid],
p1.[subject],
p1.[message],
p1.[views],
p1.[parentid]
order by LastUpdate desc
使用以下类:
public class ForumPost : PersistedObject
{
public int Views { get; set; }
public string Message { get; set; }
public string Subject { get; set; }
public ForumPost Parent { get; set; }
public UserAccount UserAccount { get; set; }
public IList<ForumPost> Replies { get; set; }
}
umpost:PersistedObject的公共类
{
公共int视图{get;set;}
公共字符串消息{get;set;}
公共字符串主题{get;set;}
public ForumPost父项{get;set;}
公共用户帐户{get;set;}
公共IList回复{get;set;}
}
如何在LINQ中复制这样的查询?我尝试了几种变体,但似乎无法获得正确的连接语法。这只是一个对于LINQ来说太复杂的查询的例子吗?如何使用嵌套查询完成
查询的目的是查找最近更新的帖子,即回复帖子会将其排在列表的顶部。回复由ParentID列定义,该列是自引用的。LINQ中左连接的语法是: (我把它放在VB.NET中): 诸如此类
Ju我发现NHibernate LINQ支持不包括连接。再加上对复杂LINQ查询显然缺乏经验,我采取了以下解决方法:
- 将修改的列添加到posts表中
- 回复时,更新父级的修改列以匹配回复的创建列
- 按排序并检索用于后期显示的已修改列的值
把这个留到这里,以后作为答案。真的吗,谁会对一篇6个月前的帖子投反对票,尤其是一篇回答自己问题的帖子?至少要留个条子,说明为什么你觉得自己不得不做这样一件蠢事。
Dim query = From table1 in myTable.AsEnumarable 'Can be a collection of your object
Group join table2 in MyOtherTable.AsEnumerable
On table1.Field(Of Type)("myfield") Equals table2.Field(Of Type)("myfield")
In temp
From table2 in temp.DefaultIsEmpty()
Where table1.Field(Of Type)("Myanotherfield") is Nothing 'exemple
Select New With { .firstField = table1.Field(Of Type)("Myanotherfield")
.secondField = table2.Field(Of Type)("Myanotherfield2")}