Tuesday, 17 June 2014

multiple-search-criteria-searching-using-linq-to-sql, search with multiple criteria in mvc4










: /// <summary>

2: /// Gets a LINQ to SQL Query according the provided parameters


3: /// </summary>

4: /// <param name="postsQuery"></param>


5: /// <param name="title"></param>

6: /// <param name="tags"></param>


7: /// <param name="createdOn"></param>

8: /// <param name="bodyText"></param>


9: /// <returns></returns>

10: private IQueryable<Post> GetPostsQuery(IQueryable<Post> postsQuery,


11: string title,

12: string tags,


13: string bodyText,

14: DateTime? createdOn)


15: {

16: if (!string.IsNullOrEmpty(title))


17: postsQuery = postsQuery.Where(p => p.Title.Contains(title));

18:


19: if (!string.IsNullOrEmpty(tags))

20: postsQuery = postsQuery.Where(p => p.Tags.Contains(tags));


21:

22: if (!string.IsNullOrEmpty(bodyText))


23: postsQuery = postsQuery.Where(p => p.Body.Contains(bodyText));

24:


25: if (createdOn.HasValue && createdOn.Value > DateTime.MinValue)

26: postsQuery = postsQuery.Where(p => p.CreatedOn.Value.Date == createdOn.Value.Date);


27:

28: return postsQuery;


29: }

Listing 4: IQueryable<Post> GetPostsQuery, extends and returns the IQueryable<Post> query

Listing 5 contains the method GetpostsPagingQuery. This method also extends and returns the query. LINQ to SQL provides paging with the Skip (skip all rows untill) and Take (take n number of rows) methods. And this method uses these methods to extends the query with paging capabilities.


1: private IQueryable<Post> GetPostsPagingQuery(IQueryable<Post> postsQuery,

2: int? startRow,


3: int? rowCount)

4: {


5: if ((startRow.HasValue) && (rowCount.HasValue && rowCount.Value > 0))

6: postsQuery = postsQuery.Skip((int)startRow).Take((int)rowCount);


7:

8: return postsQuery;


9: }

Listing 5: Adds paging to query, using Skip and Take methods

No comments:

Post a Comment