EF的泛型封装 写的很好 转自Fly_Elephant http://www.cnblogs.com/xiaofeixiang/p/4188600.html?utm_source=tuicool
2015-05-15 21:40
471 查看
Entity Framework本身的增删改查其实 已经很方便了,不过做项目的时候用的多了也就觉得有点累了,每个业务实体基本上都涉及到到了增删改查这四个基本的要素,至于封装每个公司可能都不一样,接口,设计模式都用的眼花缭乱,我闲来没事就搞个简单的封装Helper,Github上也有关于EF的扩展Libray,具体没有用过,公司的有自己的封装,自己也没怎么弄,具体地址:https://github.com/loresoft/EntityFramework.Extended.
首先来看段代码,model和context是从数据中直接生成,你可以选择自己习惯的方式:
如果每个业务实体都这么写一遍,估计公司水准有待提高,而且开发的也该跳起来骂人,本人只是简单封装下新建一个EFHelper,实际开发会封装的更多,不过底层处理是不变的
调用:
简单调用,第二个方式除了分页之外,主要是查询的时候指定一定OrderBy的类型,也就是TKey:
调用:
调用:
完整的EFHelper:
个人Demo难免有表达不当或者技术失误的地方,如有不当,请多多指出,感激不尽~
首先来看段代码,model和context是从数据中直接生成,你可以选择自己习惯的方式:
//新增 User addUser = new User(); addUser.PersonID = 3; addUser.UserName = "keso"; dbContext.Entry<User>(addUser).State = EntityState.Added; dbContext.SaveChanges(); //修改 User updateUser = new User(); dbContext.Users.Where(item => item.ID == 2).OrderBy(item => item.ID); updateUser.UserName = updateUser.UserName + "测试"; dbContext.Entry<User>(updateUser).State = EntityState.Modified; dbContext.SaveChanges(); //删除 User delUser = dbContext.Users.Where(item => item.ID == 2).First(); dbContext.Entry<User>(delUser).State = EntityState.Deleted; dbContext.SaveChanges();
如果每个业务实体都这么写一遍,估计公司水准有待提高,而且开发的也该跳起来骂人,本人只是简单封装下新建一个EFHelper,实际开发会封装的更多,不过底层处理是不变的
class EFHelpler<T> where T : class { //... }
新增
方法:/// <summary> /// 实体新增 /// </summary> /// <param name="model"></param> public void add(params T[] paramList) { foreach (var model in paramList) { dbContext.Entry<T>(model).State = EntityState.Added; } dbContext.SaveChanges(); }
调用:
EFHelpler<User> helper = new EFHelpler<User>(); BaseContext dbContext = new BaseContext(); //新增 List<User> listUser = new List<User>(); for (int i = 0; i < 2; i++) { User user = new User(); user.PersonID = i; user.UserName = "FlyElehant" + i; listUser.Add(user); } helper.add(listUser.ToArray()); Console.WriteLine("新增成功");
查询
查询分了两种,一种是简单的查询,一种是分页的:/// <summary> /// 实体查询 /// </summary> public IEnumerable<T> getSearchList(System.Linq.Expressions.Expression<Func<T, bool>> where) { return dbContext.Set<T>().Where(where); } /// <summary> /// 实体分页查询 /// </summary> /// <typeparam name="TKey"></typeparam> /// <param name="where"></param> /// <param name="orderBy"></param> /// <param name="pageSize"></param> /// <param name="pageIndex"></param> /// <returns></returns> public IEnumerable<T> getSearchListByPage<TKey>(Expression<Func<T, bool>> where, Expression<Func<T, TKey>> orderBy, int pageSize, int pageIndex) { return dbContext.Set<T>().Where(where).OrderByDescending(orderBy).Skip((pageIndex - 1) * pageSize).Take(pageSize); }
简单调用,第二个方式除了分页之外,主要是查询的时候指定一定OrderBy的类型,也就是TKey:
var query = helper.getSearchList(item => item.UserName.Contains("keso")); var queryMulti = helper.getSearchListByPage<int>(item => item.UserName.Contains("FlyElehant"), order => order.PersonID, 2, 1); query = queryMulti; foreach (User user in query) { Console.WriteLine(user.UserName); }
修改
修改代码稍微读了几行,主要是用到了一下反射:/// <summary> /// 按照条件修改数据 /// </summary> /// <param name="where"></param> /// <param name="dic"></param> public void update(Expression<Func<T, bool>> where, Dictionary<string, object> dic) { IEnumerable<T> result = dbContext.Set<T>().Where(where).ToList(); Type type = typeof(T); List<PropertyInfo> propertyList = type.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance).ToList(); //遍历结果集 foreach (T entity in result) { foreach (PropertyInfo propertyInfo in propertyList) { string propertyName = propertyInfo.Name; if (dic.ContainsKey(propertyName)) { //设置值 propertyInfo.SetValue(entity, dic[propertyName], null); } } } dbContext.SaveChanges(); }
调用:
Dictionary<string,object> dic=new Dictionary<string,object>(); dic.Add("PersonID",2); dic.Add("UserName","keso"); helper.update(item => item.UserName.Contains("keso"), dic); Console.WriteLine("修改成功");
删除
方法:/// <summary> /// 实体删除 /// </summary> /// <param name="model"></param> public void delete(params T[] paramList) { foreach (var model in paramList) { dbContext.Entry<T>(model).State = EntityState.Deleted; } dbContext.SaveChanges(); }
调用:
var query = helper.getSearchList(item => item.UserName.Contains("keso")); helper.delete(query.ToArray());
完整的EFHelper:
class EFHelpler<T> where T : class
{
BaseContext dbContext = new BaseContext();
/// <summary> /// 实体新增 /// </summary> /// <param name="model"></param> public void add(params T[] paramList) { foreach (var model in paramList) { dbContext.Entry<T>(model).State = EntityState.Added; } dbContext.SaveChanges(); }/// <summary> /// 实体查询 /// </summary> public IEnumerable<T> getSearchList(System.Linq.Expressions.Expression<Func<T, bool>> where) { return dbContext.Set<T>().Where(where); } /// <summary> /// 实体分页查询 /// </summary> /// <typeparam name="TKey"></typeparam> /// <param name="where"></param> /// <param name="orderBy"></param> /// <param name="pageSize"></param> /// <param name="pageIndex"></param> /// <returns></returns> public IEnumerable<T> getSearchListByPage<TKey>(Expression<Func<T, bool>> where, Expression<Func<T, TKey>> orderBy, int pageSize, int pageIndex) { return dbContext.Set<T>().Where(where).OrderByDescending(orderBy).Skip((pageIndex - 1) * pageSize).Take(pageSize); }/// <summary> /// 实体删除 /// </summary> /// <param name="model"></param> public void delete(params T[] paramList) { foreach (var model in paramList) { dbContext.Entry<T>(model).State = EntityState.Deleted; } dbContext.SaveChanges(); }/// <summary> /// 按照条件修改数据 /// </summary> /// <param name="where"></param> /// <param name="dic"></param> public void update(Expression<Func<T, bool>> where, Dictionary<string, object> dic) { IEnumerable<T> result = dbContext.Set<T>().Where(where).ToList(); Type type = typeof(T); List<PropertyInfo> propertyList = type.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance).ToList(); //遍历结果集 foreach (T entity in result) { foreach (PropertyInfo propertyInfo in propertyList) { string propertyName = propertyInfo.Name; if (dic.ContainsKey(propertyName)) { //设置值 propertyInfo.SetValue(entity, dic[propertyName], null); } } } dbContext.SaveChanges(); }}
个人Demo难免有表达不当或者技术失误的地方,如有不当,请多多指出,感激不尽~
相关文章推荐
- https://www.cnblogs.com/wt645631686/p/6867651.html?utm_source=itdadao&utm_medium=referral
- netty的工作流程https://www.cnblogs.com/chenyangyao/p/netty.html?utm_source=itdadao&utm_medium=referral
- 红黑树(四)之 C++的实现 http://www.cnblogs.com/skywang12345/p/3624291.html?utm_source=tuicool&utm_medium=refe
- 对WebService的一些封装技巧总结(http://www.cnblogs.com/sxwgf/archive/2011/07/10/something-about-webservice.html
- 一个封装比较完整的FTP类——clsFTP (转:http://www.cnblogs.com/name-lh/archive/2007/04/28/731528.html)
- http://www.cnblogs.com/dumuqiao/p/3654702.html?utm_source=tuicool&utm_medium=referral
- sql 分页(原:http://www.cnblogs.com/fly_zj/archive/2010/07/06/1772536.html)
- "翻身做主"--给自己的软件制作注册码 -源自http://www.cnblogs.com/ziyiFly/archive/2008/09/22/1296096.html
- 破解EXCEL2007的密码转载 www.cnblogs.com/micccn/archive/2008/09/26/1299453.html
- 归并排序(转载http://www.cnblogs.com/jillzhang/archive/2007/09/16/894936.html)
- http://www.cnblogs.com/yjf512/p/3164400.html
- python 的日志logging模块学习 (转自:http://www.cnblogs.com/dkblog/archive/2011/08/26/2155018.html)
- 非阻塞Connect对于select时应注意问题 http://www.cnblogs.com/zhangmo/archive/2013/04/02/2995824.html
- http://www.ibm.com/developerworks/cn/opensource/os-cn-quartz/index.html
- Oracle数据库备份与恢复之一:exp/imp(原文http://www.cnblogs.com/sungod/archive/2011/03/13/1983090.html)
- 静态 http://www.cnblogs.com/lzjsky/archive/2011/01/24/1943199.html
- http://www.cnblogs.com/zhaoyang/archive/2012/01/07/2315436.html
- http://www.cnblogs.com/dotey/archive/2011/05/10/2041966.html
- ACM基本输入输出(转自http://www.cnblogs.com/chenqiangjsj/archive/2011/04/08/2009452.html)
- ToBase64String()的问题 --引用自http://www.cnblogs.com/afxucamd/archive/2004/02/10/1128.html