联表查询,判断追加条件,对集合分页
public ActionResult Index(string titleName, string nickName, int pageIndex = 1) { var data = from m in _db.AppArticleComment join o in _db.AppArticle on m.ArticleId equals o.ArticleId where (string.IsNullOrEmpty(nickName) ? true : m.NickName == nickName)//在此判断加条件,当变量值null需要转为整型时会抱异常 select new AppArticleCommentModel() { Id = m.Id, OId = m.OId, MId = m.MId, NickName = m.NickName, Comment = m.Comment, Good = m.Good, Created = m.Created, IsHorizontal = m.IsHorizontal, Version = m.Version, From = m.From, ArticleName = o.Title }; if (!string.IsNullOrEmpty(titleName)) { //也可在此判断添追加条件 data = data.Where(m => m.ArticleName.Contains(titleName)); } int total = 0; int pageSize = 10; //对集合进行分页 var query = data.OrderByDescending(m => m.Created) .Skip(pageSize * (pageIndex - 1)).Take(pageSize); var list = query.ToList(); total = data.Count(); PagingHelper<AppArticleCommentModel> dataPaging = new PagingHelper<AppArticleCommentModel>(10, list);//初始化分页器 dataPaging.PageIndex = pageIndex;//指定当前页 dataPaging.PageCount = (int)Math.Ceiling(total / (double)pageSize); dataPaging.PageSize = pageSize; dataPaging.TotalCount = total; return View(dataPaging);//返回分页器实例到视图 }