2016-07-15 5 views
0

私はいくつかの内容をリストしたページを持っています。以下のコードでページのページングを作成しました。しかし、私はRowCountを取得するために2番目のクエリを作成しなければならないことがわかります。データベースへの2回目のクエリなしでページングを実行できますか?Asp.net WebフォームとEntity Frameworkの単一のクエリでページング

// ContentList.aspx.cs 
MySiteEntities db = new MySiteEntities(); 

my_ContentList = db.Content.Where(it => it.Language == "En" && it.Type == QueryType && it.Active == true && it.Deleted == false).OrderBy(it => it.Sort).Skip(PageSize * (PageIndex - 1)).Take(PageSize).ToList(); 

RowCount = db.Content.Where(it => it.Language == "En" && it.Type == QueryType && it.Active == true && it.Deleted == false).Count(); 

PageCount = RowCount/PageSize + 1; 




// ContentList.aspx 

<%if (RowCount > PageSize) {%> 

    <%if (PageIndex > 1) {%><a href="Content/<%=Type%>/<%=PageIndex-1%>" class="page-numbers prev">Previous</a><%}%> 

    <% 
    int Position = 1; 
    do 
    { 
    %> 
     <a href="Content/<%=Type%>/<%=Position%>" class="page-numbers <%if (Position == PageIndex) {%>current<%}%>"><%=Position%></a> 
    <% 
    Position++; 
    } while (Position < PageCount+1); 
    %> 

    <%if (PageIndex != PageCount) {%><a href="Content/<%=Type%>/<%=PageIndex+1%>" class="page-numbers next">Next</a><%}%> 

<%}%> 

答えて

0

解決策1:クエリを次のようにEntityFramework.Extendedライブラリから 使用、これは溶液2からより良いパフォーマンスです!

var query = db.Content.Where(it => it.Language == "En" && it.Type == QueryType && it.Active == true && it.Deleted == false); 

var countQuery= query.FutureCount(); 

var itemsQuery= query.OrderBy(it => it.Sort) 
    .Skip(PageSize * (PageIndex - 1)) 
    .Take(PageSize) 
    .Future(); 

int RowCount = countQuery.Value; 
var my_ContentList = itemsQuery.ToList(); 

ソリューション2: 次のクエリでは、データベースへの1回の旅行で数とページの結果を取得しますが、あなたはのSQLProfilerでSQLを確認した場合、あなたはそれが非常にきれいではないことがわかります。

var query = db.Content.Where(it => it.Language == "En" && it.Type == QueryType && it.Active == true && it.Deleted == false); 

var pageResult = query.OrderBy(it => it.Sort) 
    .Skip(PageSize * (PageIndex - 1)) 
    .Take(PageSize) 
    .GroupBy (p => new { Total = query.Count() }) 
    .First(); 

int RowCount = pageResult .Key.Total; 
var my_ContentList = pageResult .Select(p => p); 

チェックこの link1link2

関連する問題