代码之家  ›  专栏  ›  技术社区  ›  Dylan Beattie

如何使用Castle ActiveRecord预加载具有父子自引用的记录?

  •  0
  • Dylan Beattie  · 技术社区  · 17 年前

    我的SQL表如下所示:

    CREATE TABLE Page (
        Id int primary key,
        ParentId int, -- refers to Page.Id
        Title varchar(255),
        Content ntext
    )
    

    [ActiveRecord]
    public class Page {
    
        [PrimaryKey]
        public int Id { get; set; }
    
        [BelongsTo("Parent")]
        public virtual Page Parent { get; set; }
    
        [Property]
        public string Title { get; set; }
    
        [Property]
        public string Content { get; set; }
    
        [HasMany(typeof(Page), "Parent", "Page")]
        public IList<Page> Children { get; set; }
    }
    

    我正在使用ActiveRecord检索树根,代码如下:

    var rootPages = new SimpleQuery<Page>(@"from Page p where p.Parent is null");
    return(rootPages.Execute());
    

    这为我提供了正确的对象图,但SQL探查器跟踪显示,子页面是由树中每个非叶节点的单独查询加载的。

    ("SELECT * FROM Page") 然后对内存中的对象进行排序,以获得所需的父子关系?

    2 回复  |  直到 17 年前
        1
  •  2
  •   oillio    16 年前

    最简单的方法是获取整个表,然后过滤结果。如果您使用的是linq,那么这非常简单。

    var AllPages = ActiveRecordMediator<Page>.FindAll();
    var rootPages = AllPages.Where(p => p.Parent == null);
    
        2
  •  -1
  •   Neil Hewitt    17 年前

    试试这个:

    var rootPages = new SimpleQuery<Page>(@"from Page p left join fetch p.Children where p.Parent is null");
    return(rootPages.Execute());
    

    这将导致在初始查询期间填充结果集中每个页面的子集合,从而将整体查询负载减少到单个查询。