Castle ActiveRecord를 사용하여 부모-자식 자기 참조로 레코드를 어떻게 사전로드 할 수 있습니까?

StackOverflow https://stackoverflow.com/questions/279392

문제

내 SQL 테이블은 다음과 같습니다.

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

내 ActiveRecord 모델에서 다음 클래스에 대한지도 :

[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 프로파일 러 트레이스는 트리의 모든 비 잎 노드에 대해 하위 페이지가 별도의 쿼리로로드되고 있음을 보여줍니다.

ActiveRecord를 어떻게 전부로드 할 수 있습니까? ("SELECT * FROM Page") 그런 다음 메모리 내 개체를 정렬하여 필요한 부모-자식 관계를 제공합니까?

도움이 되었습니까?

해결책

이 작업을 수행하는 가장 쉬운 방법은 전체 테이블을 가져온 다음 결과를 필터링하는 것입니다. LINQ를 사용하는 경우 매우 쉽습니다.

var AllPages = ActiveRecordMediator<Page>.FindAll();
var rootPages = AllPages.Where(p => p.Parent == null);

다른 팁

이 시도:

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

이렇게하면 초기 쿼리 중에 결과 세트에서 각 페이지의 어린이 수집이 채워져 전체 쿼리로드가 단일 쿼리로 줄어 듭니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top