Дозвуковой запрос, я отстой! - PullRequest
       4

Дозвуковой запрос, я отстой!

1 голос
/ 27 сентября 2010

Я использую Subson 2.2 в одном из моих проектов.У меня есть раздел комментариев, где я запрашиваю одну таблицу под названием Комментарии.Сначала я запрашиваю все записи с ParentId = 0, а затем в операторе foreach я запрашиваю все записи с ParentId = currentRecord.Id.Теперь я знаю, что это плохая привычка, но я не знаю, как обойти это в одном запросе, используя SubSonic, может быть, я упускаю что-то важное здесь.направление.Спасибо за ваше время!

С уважением, Марк

     [WebMethod]
    public List<Comment> GetComments(int aid)
    {          

        DAL.CommentCollection coll = new DAL.CommentCollection();
        SubSonic.Query qry = new SubSonic.Query(DAL.Comment.Schema);
        qry.AddWhere(DAL.Comment.Columns.ArticleID, aid);
        qry.AddWhere(DAL.Comment.Columns.ParentID, 0);
        qry.AddWhere(DAL.Comment.Columns.IsActive, true);
        qry.AddWhere(DAL.Comment.Columns.IsDeleted, false);
        qry.ORDER_BY(DAL.Comment.Columns.CreatedOn, "Asc");
        qry.PageSize = Classes.Settings.Controls.Comments.GetCommentsPerPage();
        coll.LoadAndCloseReader(qry.ExecuteReader());
        foreach (DAL.Comment item in coll)
        {
            Comment c = new Comment();
            c.Date = Convert.ToDateTime(item.CreatedOn).ToLongDateString();
            c.UserName = item.User.UserName;
            c.FullText = item.FullText;
            c.Gravatar = Classes.Data.HashString(item.User.GravatarId);
            c.IsSub = false;
            c.CommentId = (int)item.CommentID;
            comments.Add(c);

            //Get replies
            GetReplies((int)item.CommentID, aid);
        }

        return comments;
    }

    private void GetReplies(int CommentId, int aid)
    {
        DAL.CommentCollection coll = new DAL.CommentCollection();
        SubSonic.Query qry = new SubSonic.Query(DAL.Comment.Schema);
        qry.AddWhere(DAL.Comment.Columns.ArticleID, aid);
        qry.AddWhere(DAL.Comment.Columns.ParentID, CommentId);
        qry.AddWhere(DAL.Comment.Columns.IsActive, true);
        qry.AddWhere(DAL.Comment.Columns.IsDeleted, false);
        qry.ORDER_BY(DAL.Comment.Columns.CreatedOn, "Asc");
        qry.PageSize = Classes.Settings.Controls.Comments.GetCommentsPerPage();
        coll.LoadAndCloseReader(qry.ExecuteReader());
        foreach (DAL.Comment item in coll)
        {
            Comment c = new Comment();
            c.Date = Convert.ToDateTime(item.CreatedOn).ToLongDateString();
            c.UserName = item.User.UserName;
            c.FullText = item.FullText;
            c.Gravatar = Classes.Data.HashString(item.User.GravatarId);
            c.IsSub = true;
            c.CommentId = (int)item.CommentID;
            comments.Add(c);
        }
    }

1 Ответ

0 голосов
/ 04 октября 2010

Если все элементы связаны по идентификатору статьи, просто загрузите их все один раз и отсортируйте в памяти.

//Load all article comments from the Database
DAL.CommentCollection dbComments = new Select()
    .From(DAL.Comment.Schema)
        .Where(DAL.Comment.ArticleIDColumn).IsEqualTo(aid)
            .And(DAL.Comment.IsActiveColumn).IsEqualTo(true)
            .And(DAL.Comment.IsDeletedColumn).IsEqualTo(false)
        .OrderBy(DAL.Comment.Columns.ParentID, DAL.Comment.Columns.CreatedOn)
    .ExecuteAsCollection<DAL.CommentCollection>();

//Now sort all comments however needed
DAL.CommentCollection parents = new DAL.CommentCollection();
foreach (DAL.Comment parent in dbComments)
{
    if (parent.ParentID == 0)
    {
        parents.add(parent);
    }
    else
        break; //because of the way we ordered the items above, all parents should now be processed
}

//now loop through the parent collection and add children beneath parents to the final collection
foreach (DAL.Comment parent in parents)
{
    comments.add(parent);
    foreach (DAL.Comment possibleChild in dbComments)
    {
        if (possibleChild.ParentID > 0 && possibleChild.ParentID == parent.ID)
        {
            comments.add(possibleChild);
        }
    }
 }

 return comments;
...