参考:
http://www.cnblogs.com/weilengdeyu/p/3588472.html
http://blog.youkuaiyun.com/xjn030594/article/details/8946996
改为自己的:
BaseDAL
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;
using System.Linq.Expressions;
using LinqKit;
namespace DAL
{
public class BaseDAL<T> where T:class,new()
{
TestDb db = new TestDb();
/// <summary>
/// 新增
/// </summary>
/// <param name="entity">实体</param>
/// <returns>返回受影响行数</returns>
public int Add(T entity)
{
db.Entry<T>(entity).State = EntityState.Added;
return db.SaveChanges();
}
/// <summary>
/// 修改
/// </summary>
/// <param name="entity">实体</param>
/// <returns>返回受影响行数</returns>
public int Update(T entity)
{
db.Set<T>().Attach(entity);
db.Entry<T>(entity).State =EntityState.Modified;
return db.SaveChanges();
}
/// <summary>
/// 删除
/// </summary>
/// <param name="entity">实体</param>
/// <returns>返回受影响行数</returns>
public int Delete(T entity)
{
db.Set<T>().Attach(entity);
db.Entry<T>(entity).State = EntityState.Deleted;
return db.SaveChanges();
}
/// <summary>
/// 根据条件删除
/// </summary>
/// <param name="deleWhere">删除条件</param>
/// <returns>返回受影响行数</returns>
public int DeleteByConditon(Expression<Func<T, bool>> deleWhere)
{
List<T> entitys = db.Set<T>().Where(deleWhere).ToList();
entitys.ForEach(m => db.Entry<T>(m).State = EntityState.Deleted);
return db.SaveChanges();
}
/// <summary>
/// 查找单个
/// </summary>
/// <param name="id">主键</param>
/// <returns></returns>
public T GetSingleById(int id)
{
return db.Set<T>().Find(id);
}
/// <summary>
/// 获取所有实体集合
/// </summary>
/// <returns></returns>
public List<T> GetAll()
{
return db.Set<T>().ToList<T>();
}
/// <summary>
/// 根据条件查询实体集合
/// </summary>
/// <param name="seleWhere">查询条件 lambel表达式</param>
/// <returns></returns>
public List<T> GetList(Expression<Func<T, bool>> seleWhere)
{
return db.Set<T>().Where(seleWhere).ToList();
}
/// <summary>
/// 根据条件查询实体集合并排序
/// </summary>
/// <typeparam name="Tkey"> 由 orderWhere 表示的函数返回的键类型</typeparam>
/// <param name="seleWhere">查询条件</param>
/// <param name="orderWhere">用于从元素中提取键的函数</param>
/// <returns></returns>
public List<T> GetListOrder<Tkey>(Expression<Func<T, bool>> seleWhere, Expression<Func<T, Tkey>> orderWhere)
{
return db.Set<T>().Where(seleWhere).OrderBy(orderWhere).ToList();
}
/// <summary>
/// 根据条件查询实体集合并排序(分页)
/// </summary>
/// <typeparam name="Tkey"> 由 orderWhere 表示的函数返回的键类型</typeparam>
/// <param name="seleWhere">查询条件</param>
/// <param name="orderWhere">用于从元素中提取键的函数</param>
/// <returns></returns>
public List<T> GetListPagedOrder<Tkey>(int pageIndex, int pageSize, Expression<Func<T, bool>> seleWhere, Expression<Func<T, Tkey>> orderWhere, out int totalcount)
{
totalcount = db.Set<T>().AsExpandable().Where(seleWhere).Count();//获取总数
//需要增加AsExpandable(),否则查询的是所有数据到内存,然后再排序 AsExpandable是linqkit.dll中的方法
return db.Set<T>().AsExpandable().Where(seleWhere).OrderBy(orderWhere).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
}
}
}
帮助类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using log4net.Core;
using System.Linq.Expressions;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using System.Text.RegularExpressions;
namespace Model.Common
{
/// <summary>
/// 异常帮助类 封装 try catch操作和统一调用 增删改 方法
/// </summary>
public class ExceptionHelper
{
static log4net.ILog log = log4net.LogManager.GetLogger("TrueLore");
static JavaScriptSerializer JsonSerializer = new JavaScriptSerializer();//json转换类
/// <summary>
/// 无返回值无参数的方法调用
/// </summary>
/// <param name="action"></param>
public void Invoke(Action action)
{
try
{
action();
}
catch (Exception ex)
{
log.Error(ex.Message);
}
}
/// <summary>
/// 有返回值无参数的方法调用
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="func"></param>
/// <returns></returns>
public static T Invoke<T>(Func<T> func)
{
try
{
return func();
}
catch (Exception ex)
{
log.Error(ex.Message);
return default(T);
}
}
/// <summary>
/// 公共的获取非查询执行结果的方法
/// </summary>
/// <param name="op">操作方法</param>
/// <param name="nu">newuser对象</param>
/// <param name="errormsg">错误信息</param>
/// <returns>json结果</returns>
public static string GetNoQueryJsonResult<T>(Func<T,int> op, T nu, string errormsg,bool isvalid)
{
EasyResult er = new EasyResult();
er.success = false;
try
{
if (isvalid)
{
int i = op(nu);
if (i > 0)
{
er.success = true;
}
else
{
er.errorMsg = errormsg;
}
}
else
{
er.errorMsg = "验证失败,请检查数据";
}
}
catch (Exception ex)
{
er.errorMsg = ex.Message;
log.Error(ex.Message,ex);
}
return JsonSerializer.Serialize(er);
}
}
/// <summary>
/// 泛型 异常帮助类 封装 try catch操作和统一调用 查询 方法
/// </summary>
/// <typeparam name="ModelType"></typeparam>
public class ExceptionHelper<ModelType,Tkey>
{
// public delegate List<ModelType> FuncEx(int t1, int t2, Dictionary<string, string> t3, out int t4);
//public delegate List<ModelType> FuncEx(Expression<Func<ModelType, bool>> seleWhere, Expression<Func<ModelType, Tkey>> orderWhere);
public delegate List<ModelType>
FuncEx(int pageIndex, int pageSize, Expression<Func<ModelType, bool>> seleWhere, Expression<Func<ModelType, Tkey>> orderWhere, out int totalcount);
static log4net.ILog log = log4net.LogManager.GetLogger("TrueLore");
static JavaScriptSerializer JsonSerializer = new JavaScriptSerializer();//json转换类
public ExceptionHelper(string classname)
{
log = log4net.LogManager.GetLogger(classname);
}
/// <summary>
/// 公共的获取查询执行结果的方法(分页)
/// </summary>
/// <param name="op">操作方法</param>
/// <param name="pageIndex">页码</param>
/// <param name="pageSize">每页记录数</param>
/// <param name="dicCondition">查询条件</param>
/// <param name="totalcount">总数</param>
/// <returns>json数据集合</returns>
public static string GetQueryJsonResult(FuncEx op, int pageIndex, int pageSize, Expression<Func<ModelType, bool>> seleWhere,
Expression<Func<ModelType, Tkey>> orderWhere, out int totalcount)
{
totalcount = 0;
try
{
List<ModelType> lsnu = op(pageIndex, pageSize, seleWhere,orderWhere, out totalcount);
EasyDataGrid<ModelType> edg = new EasyDataGrid<ModelType>();
edg.total = totalcount;//总记录数
edg.rows = lsnu;//行数据
string str = JsonSerializer.Serialize(edg);
str = Regex.Replace(str, @"\\/Date\((\d+)\)\\/", match =>
{
DateTime dt = new DateTime(1970, 1, 1);
dt = dt.AddMilliseconds(long.Parse(match.Groups[1].Value));
dt = dt.ToLocalTime();
return dt.ToString("yyyy-MM-dd");
});
return str;
}
catch (Exception ex)
{
log.Error(ex.Message, ex);
}
return "";
}
}
}
使用
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BLL;
using Model.DataModel;
using Model.Common;
using System.Web.Script.Serialization;
using System.Text.RegularExpressions;
using System.Linq.Expressions;
using LinqKit;
namespace MVC_EASYUI_TEST.Controllers
{
public class UserManageController : Controller
{
BaseBLL<NewUser> bll = new BaseBLL<NewUser>();
JavaScriptSerializer JsonSerializer = new JavaScriptSerializer();//json转换类
public ActionResult Index()
{
return View();
}
/// <summary>
/// 获取用户列表
/// </summary>
/// <returns></returns>
public ActionResult GetList(int page,int rows,string username="")
{
int count = 0;
Dictionary<string, string> dicCondition = new Dictionary<string, string>();//查询条件
dicCondition.Add("username", username);
Expression<Func<NewUser, bool>> searchPredicate = PredicateBuilder.True<NewUser>();
searchPredicate = searchPredicate.And(c => c.UserName.Contains(username));
//searchPredicate = searchPredicate.And(c => c.Sex == true);
Expression<Func<NewUser, int>> keySelector = u => u.UserId;
string str = ExceptionHelper<NewUser, int>.GetQueryJsonResult(bll.GetListPaged, page, rows, searchPredicate, keySelector, out count);
return Content(str);
}
/// <summary>
/// 新增用户页面 get请求
/// </summary>
/// <returns></returns>
public ActionResult AddUser()
{
ViewBag.Title = "新增用户";
ViewBag.ConfirmBtnTitle = "新增";
return View("EditUser");
}
/// <summary>
/// 新增用户页面 post请求
/// </summary>
/// <param name="nu"></param>
/// <returns></returns>
[HttpPost]
public ActionResult AddUser(NewUser nu)
{
ModelState.Remove("UserId");//不验证userid
return Content(ExceptionHelper.GetNoQueryJsonResult(bll.Add, nu, "添加用户失败", ModelState.IsValid));
}
/// <summary>
/// 更新用户页面 get请求
/// </summary>
/// <param name="userid"></param>
/// <returns></returns>
public ActionResult UpdateUser(int userid)
{
NewUser nu = bll.GetSingleById(userid);
ViewBag.Title = "修改用户";
ViewBag.ConfirmBtnTitle = "修改";
return View("EditUser",nu);
}
/// <summary>
/// 更新用户页面 post请求
/// </summary>
/// <param name="nu"></param>
/// <returns></returns>
[HttpPost]
public ActionResult UpdateUser(NewUser nu)
{
return Content(ExceptionHelper.GetNoQueryJsonResult(bll.Update, nu, "更新用户失败",ModelState.IsValid));
}
/// <summary>
/// 删除用户
/// </summary>
/// <param name="UserId"></param>
/// <returns></returns>
[HttpPost]
public ActionResult DeleteUser(int UserId)
{
NewUser nu = new NewUser();
nu.UserId = UserId;
return Content(ExceptionHelper.GetNoQueryJsonResult(bll.Delete, nu, "删除用户失败", ModelState.IsValid));
}
}
}