Asp.Net MVC多表联合查询分页+多条件查询方法

 //代码不全,随意记录笔记

public ActionResult GetListJson(int page, int limit,string title,int passed=-1, int good =-1,int classID=-1,string t1="",string t2="")
        {
            //list管理页面用?page=3&limit=15&title=ceshi
            var pageIndex = page;
            var pageSize = limit;
            var counts = 0;
            Expression<Func<News, bool>> whereLamdba = i => true;
            if (!string.IsNullOrEmpty(title))
            {
                whereLamdba = whereLamdba.And(m => m.title.Contains(title));
            }
            if (passed>-1)
            {
                whereLamdba = whereLamdba.And(m => m.passed == passed);
            }
            if (good > -1)
            {
                whereLamdba = whereLamdba.And(m => m.good == good);
            }
            if (classID > -1)
            {
                var listID = new NewsClassBLL().GetIDList(classID.ToString());
                whereLamdba = whereLamdba.And(m => listID.Contains(m.classID));
            }
            if (!string.IsNullOrEmpty(t1))
            {
                var date1 = ConvertHelper.ConvertToDateTime(t1, DateTime.Now);
                whereLamdba = whereLamdba.And(m => m.timeShow>= date1);
            }
            if (!string.IsNullOrEmpty(t2))
            {
                var date2 = ConvertHelper.ConvertToDateTime(t2 + " 23:59:59", DateTime.Now);
                whereLamdba = whereLamdba.And(m => m.timeShow <= date2);
            }

            //多表查询分页有2种方法
        //如果返回值需要修改,则不能使用匿名类型,需要自定义一个ViewModel
//方法1: var listClass = bllNewsClass.FindList(); var list = bll.FindPageList(pageIndex, pageSize, out counts, whereLamdba, false, x => x.ID) .Join(listClass,n=>n.classID,c=>c.ID, (n, c) => new { n.ID,n.title,cname =c.name}).ToList(); //方法2: /*var sql = from n in bll.FindList().Where(whereLamdba) join c in bllNewsClass.FindList() on n.classID equals c.ID select new { n.ID, n.title, cname = c.name }; var list = sql.OrderByDescending(m => m.ID).ToPagedList(pageIndex, pageSize); counts = list.TotalItemCount;*/ ResultModel res = new ResultModel(); res.code = 0; res.data = list; res.count = counts; return Json(res, JsonRequestBehavior.AllowGet); }

 

posted @ 2021-09-14 14:46  WebApi  阅读(939)  评论(0编辑  收藏  举报
CopyRight © 博客园 WebAPI