Build dynamic LINQ?

前端 未结 4 1390
我寻月下人不归
我寻月下人不归 2020-12-21 00:45

I\'m using LINQ to query data. Consider a case where the user only wants to report on say 1 of the 3 fields? (see below)

Can anyone tell me how to build the query d

4条回答
  •  萌比男神i
    2020-12-21 01:21

    We do it by passing in a Criteria object and then build the query by appending the desired criteria using expression trees.

    IQueryable query = ctx.DataContext.Stories;
    
    if (criteria.StoryId != null) // StoryId
        query = query.Where(row => row.StoryId == criteria.StoryId);
    
    if (criteria.CustomerId != null) // CustomerId
        query = query.Where(row => row.Project.CustomerId == criteria.CustomerId);
    
    if (criteria.SortBy != null) // SortBy
        query = query.OrderBy(criteria.SortBy + " " + criteria.SortOrder.Value.ToStringForSql());
    
    if (criteria.MaximumRecords != null) // MaximumRecords
        query = query.Take(criteria.MaximumRecords.Value);
    
    var data = query.Select(row => StoryInfo.FetchStoryInfo(row));
    

    You can also take a look at the Dynamic Linq library at http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx

提交回复
热议问题