Search code examples
c#asp.netlinqlistviewlinqdatasource

Setting where clause and parameters of linqdatasource like a Linq query


i have a listview and binding it in codebehind from a linq query that selects related Keywords

MyDataContext dcxt = new MyDataContext();
string x = "searchword"; // i get x from user
var query = from ak in dcxt.WordIndexes
            where ak.Word == x
            from a in ak.Keywords
            where a.Comps.Approved &&
            a.Comps.Active &&
            a.Approved 
            orderby a.ETbm descending
            select a;

ListView1.DataSource = query;
ListView1.DataBind();

i have one-to-many relationship between WordIndexes -> Keywords, also one-to-many between Comps -> Keyswords.

now i want to use a linqdatasource, so i can let the linqdatasource handle paging. but i cant set the where clause like this linq query.

<asp:LinqDataSource ID="lds2" runat="server" 
    ContextTypeName="MyDataContext" EntityTypeName="" 
    OrderBy="" TableName="Keywords"
    Where="">
</asp:LinqDataSource>

i tried to use datapager (without linqdatasource) for paging but its very slow if the results hold alot of items. i used linqdatasource before with simpler queries, but this is a little complex for me because of relationships between tables and i dont know where to start building the where clause. any help?

Update:

I ended up using LinqDataSourceSelectEvent with a DataPager like suggested in the answer

protected void linqDS_Selecting(object sender, LinqDataSourceSelectEventArgs e)
{
    var query = from ak in dcxt.WordIndexes
                where ak.Word == x
                from a in ak.Keywords
                where a.Comps.Approved &&
                a.Comps.Active &&
                a.Approved 
                orderby a.ETbm descending
                select a;

    e.Arguments.TotalRowCount = query.Count();
    e.Result = query.Skip(DataPager1.StartRowIndex).Take(DataPager1.PageSize);
}

Solution

  • you can use LinqDataSource_Selecting event and passing the query to