mvc+dwz多表联查实现分页

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Xiaowu.Model;
using Xiaowu.BLL;
using System.Linq.Expressions;
using System.Transactions;
namespace MySQLMVCTest.Controllers
{
public class TestProductController : Controller
{
//
// GET: /TestProduct/
// wu_userBLL userbll = new wu_userBLL();
StudentDBContext db = new StudentDBContext();
public ActionResult Index(int? pageNum, int? numPerPage, IndexAtriclList model)
{

int pageIndex = pageNum.HasValue ? pageNum.Value : 1;
int pageSize = numPerPage.HasValue && numPerPage.Value > 0 ? numPerPage.Value : 2;
int recordCount = 0;
Expression<Func<w_user, bool>> userWhere = u => 1 == 1;
if (!string.IsNullOrWhiteSpace(model.wu_username))
{
userWhere = userWhere = u => u.wu_username.Contains(model.wu_username);
}
Expression<Func<s_product, bool>> proWhere = u => 1 == 1;
if (!string.IsNullOrWhiteSpace(model.sp_name))
{
proWhere = proWhere = u => u.sp_name.Contains(model.sp_name);
}
var userdata = db.w_user.Where(userWhere);
var productdata = db.s_product.Where(proWhere);
var query = from a in userdata
join m in productdata
on a.id equals m.sp_pid
orderby m.createtime descending
select new IndexAtriclList { ID = m.id, wu_username = a.wu_username, wu_nickName = a.wu_nickName, sp_name = m.sp_name, createtime = m.createtime };
var Result = query.Skip<IndexAtriclList>((pageIndex - 1) * pageSize).Take<IndexAtriclList>(pageSize);
recordCount = query.Count();
var datalist = Result.ToList();
ViewData["pageIndex"] = pageIndex;
ViewData["pageSize"] = pageSize;
ViewData["recordCount"] = recordCount;
ViewData["wu_username"] = model.wu_username;
ViewData["sp_name"] = model.sp_name;
ViewBag.sp_name = model.sp_name;
return View(datalist);


}


#region 代码注释/多表查询只能返回一个表的数据
// recordCount = Common.ToList<IndexAtriclList>(query).Count();
//var groupJoin = db.w_user.GroupJoin(db.s_product,
// a => a.id,
// m => m.sp_pid,
// (a,t) => new IndexAtriclList
// {

// ID =a.id,
// wu_username = a.wu_username,
// wu_nickName = a.wu_nickName,

// });

//var tsetlist = groupJoin.ToList();
#endregion

#region 扩展类/add/2020/11/18
public class Common
{
public static List<T> ToList<T>(IEnumerable<T> data)
{
List<T> list = new List<T>();
var propertys = System.ComponentModel.TypeDescriptor.GetProperties(typeof(T));
foreach (var item in data)
{
T t = Activator.CreateInstance<T>();
Type type = t.GetType();
foreach (System.ComponentModel.PropertyDescriptor p in propertys)
{
object o = p.GetValue(item);
t.GetType().GetProperty(p.Name).SetValue(t, o, null);
}
list.Add(t);
}
return list;
}
}
//public static List<IndexAtriclList> ChangeLinqToList<T>(IEnumerable<T> data)
//{

// //返回查询结果
// List<IndexAtriclList> retlist = new List<IndexAtriclList>();
// //获得泛型类型的属性
// var objProperty = System.ComponentModel.TypeDescriptor.GetProperties(typeof(T));
// //遍历结果集
// foreach (T t in data)
// {
// IndexAtriclList _model = new IndexAtriclList();
// Type type = _model.GetType();
// foreach (System.ComponentModel.PropertyDescriptor objProDescriptor in objProperty)
// {
// object o = objProDescriptor.GetValue(t);
// //将装箱后的值存入数据模型中对应的字段中
// type.GetField("_" + objProDescriptor.Name).SetValue(_model, o);
// }
// //给返回的结果集添加一条记录
// retlist.Add(_model);
// }

// return retlist;

//}
#endregion

public static string SuccessAlert(int statusCode, string message, string navTabId = "", string rel = "", string callbackType = "", string forwardUrl = "", string strOther = "")
{
return string.Format("{7}"statusCode":"{0}", "message":"{1}","navTabId":"{2}","rel":"{3}","callbackType":"{4}","forwardUrl":"{5}"{6}{8}", statusCode, message, navTabId, rel, callbackType, forwardUrl, strOther, "{", "}");
}
public static string ErrorAlert(int statusCode, string message)
{
return string.Format("{2}"statusCode":"{0}", "message":"{1}"{3}", statusCode, message, "{", "}");
}

}

public static class ExpressionBuilder
{
public static Expression<Func<T, bool>> And<T>(
this Expression<Func<T, bool>> first,
Expression<Func<T, bool>> second)
{
return first.AndAlso<T>(second, Expression.AndAlso);
}

public static Expression<Func<T, bool>> Or<T>(
this Expression<Func<T, bool>> first,
Expression<Func<T, bool>> second)
{
return first.AndAlso<T>(second, Expression.OrElse);
}

private static Expression<Func<T, bool>> AndAlso<T>(this Expression<Func<T, bool>> expr1, Expression<Func<T, bool>> expr2, Func<Expression, Expression, BinaryExpression> func)
{
var parameter = Expression.Parameter(typeof(T));
//var parameter2 = Expression.Parameter(typeof(T));
var ddd = expr1.Parameters;
var leftVisitor = new ReplaceExpressionVisitor(expr1.Parameters[0], parameter);
var left = leftVisitor.Visit(expr1.Body);

var rightVisitor = new ReplaceExpressionVisitor(expr2.Parameters[0], parameter);//不是用.Parameters[0]结果是不对的
var right = rightVisitor.Visit(expr2.Body);

return Expression.Lambda<Func<T, bool>>(func(left, right), parameter);
///return Expression.Lambda(func(left, right), parameter);
}

private class ReplaceExpressionVisitor
: ExpressionVisitor
{
private readonly Expression _oldValue;
private readonly Expression _newValue;

public ReplaceExpressionVisitor(Expression oldValue, Expression newValue)
{
_oldValue = oldValue;
_newValue = newValue;
}

public override Expression Visit(Expression node)
{
if (node == _oldValue)
return _newValue;
return base.Visit(node);
}
}

}


}


@{
ViewBag.Title = "多表查询demo";
}

@model IList<Xiaowu.Model.IndexAtriclList>
<form id="pagerForm" method="post" action="@Url.Action("Index")">
<input type="hidden" name="pageNum" value="@ViewData["pageIndex"]" />
<input type="hidden" name="numPerPage" value="@ViewData["pageSize"]" />
<input name="sp_name" type="hidden" value="@ViewData["sp_name"]" />
<input name="wu_username" type="hidden" value="@ViewData["wu_username"]" />
</form>
<div class="pageHeader">
<form onsubmit="return navTabSearch(this, 'TestProductList');" action="@Url.Action("Index")" method="post">
<div class="searchBar">
<ul class="searchContent">

<li>
<label>
商品名称:
</label>
<input name="sp_name" type="text" value="@ViewData["sp_name"]" />
</li>
<li>
<label>
用户名:
</label>
<input name="wu_username" type="text" value="@ViewData["wu_username"]" />
</li>
</ul>
<div class="subBar">
<ul>
<li>
<div class="buttonActive">
<div class="buttonContent">
<button type="submit">
检索
</button>
</div>
</div>
</li>
</ul>
</div>
</div>
</form>
</div>
<div class="pageContent">
<div class="panelBar">
<ul class="toolBar">
@*<li><a class="add" href="/SysUserInfo/AddUserInfo" mask="false" width="800" height="250" target="dialog" rel="SysUserInfo"><span>添加用户</span></a></li>
<li>
<a class="delete" href="/SysUserInfo/DeleteUserInfoByIds" rel="ids" target="selectedTodo" posttype="string"
title="确定要删除吗?"><span>批量删除</span></a>
</li>
<li>
<a class="delete" href="/SysUserInfo/RecoverUserInfoByIds" rel="ids" target="selectedTodo" posttype="string"
title="确定要启用吗?"><span>批量启用</span></a>
</li>*@
@*<li class="line">line</li>*@
</ul>
</div>
<table class="table" width="100%" layouth="138">
<thead>
<tr>
<th width="40">
<input type="checkbox" group="ids" class="checkboxCtrl">
</th>
<th>
编号
</th>
<th>
商品名称
</th>
<th>
用户名
</th>
<th>
昵称
</th>
<th>
创建时间
</th>
<th width="120">
操作
</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>
<input name="ids" type="checkbox" value="@item.ID" />
</td>
<td>@item.ID</td>
<td>@item.sp_name</td>
<td>@item.wu_username</td>
<td>@item.wu_nickName</td>
<td>@item.createtime</td>
<td width="120">
<a title="查看" target="dialog" class="btnInfo">详情</a>
<a title="编辑" target="dialog" href="/SysUserInfo/AddUserInfo?OID=@item.ID" class="btnEdit" mask="false" width="800" height="250"> 编辑</a>
</td>

</tr>
}
</tbody>
</table>
<div class="panelBar">
<div class="pages">
<span>每页2条,共 @ViewData["recordCount"] 条</span>
</div>
<div class="pagination" targettype="navTab" totalcount="@ViewData["recordCount"]" numperpage="@ViewData["pageSize"]" pagenumshown="10"
currentpage="@ViewData["pageIndex"]">
</div>
</div>
</div>

/// <summary>
/// 多个表之间提取的字段
/// </summary>
public class IndexAtriclList
{
public int ID { get; set; }
public string wu_username { get; set; }
public string wu_nickName { get; set; }
public string sp_name { get; set; }
public DateTime createtime { get; set; }
}

原文地址:https://www.cnblogs.com/wugh8726254/p/14003364.html