代码之家  ›  专栏  ›  技术社区  ›  Chris

LINQ自引用查询

  •  0
  • Chris  · 技术社区  · 15 年前

    我有以下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]
            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; }
    }
    

    我如何在LINQ中复制这样的查询?我尝试过几种变体,但似乎无法获得正确的连接语法。这仅仅是一个对Linq来说太复杂的查询的例子吗?可以通过使用嵌套查询来完成吗?

    查询的目的是查找最近更新的文章,即回复一篇文章会将其推到列表的顶部。答复由parentID列定义,该列是自引用的。

    2 回复  |  直到 15 年前
        1
  •  0
  •   Garcia Julien    15 年前

    LINQ中左联接的语法为:

    (我把它放在vb.net中):

    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")}
    

    像那样的

        2
  •  -1
  •   Chris    15 年前

    我发现NHibernate LINQ支持不包括连接。这一点,再加上对复杂的LINQ查询明显缺乏经验,我求助于以下工作:

    • 将修改后的列添加到Posts表中。
    • 答复时,更新父级的修改列以匹配答复的已创建列
    • 排序并检索修改后列的值以进行后期显示。

    考虑到代码的局限性,我认为这是一个非常干净的工作。我非常希望避免使用添加另一个实体、引用视图或仅针对这段特定代码使用存储过程+数据表组合。希望将所有内容都保存在实体中,并且只使用NHibernate,而此修复允许在代码气味最小的情况下进行。

    把这个留在这里稍后标记为答案。

    推荐文章