ef 仓储模式 Redis
接着写一下 上一章提到的
BaseRepositoryRedis.cs
先说说题外话:由于公司希望用到缓存来提高访问速度。那么我理所当然的想到redis。
这个无可厚非。可是当时我们的项目已经开发的差不多的了。。。。
我懒,也不可能到bll或者 dal去增加缓存代码。
于是我就想到了,既然我们的dal可以继承自BaseRepository.cs 那么一样也可以继承BaseRepositoryRedis.cs
只需要coder自己来选择是否需要缓存,需要的继承BaseRepositoryRedis,否则继承BaseRepository就好了!!!
说了这么多,那么放代码,
先创建一个RedisManager类(随便封装一下)
public class RedisManager<T> : BaseClass
{
RedisClient client = new RedisClient(RedisPath);
#region RedisHelper
/// <summary>
/// 获取
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <returns></returns>
public virtual T Get<T>(string key)
{
var q = client.Get<T>(key);
return q;
}
/// <summary>
/// 设置
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
/// <param name="expired"></param>
/// <returns></returns>
public virtual bool Set<T>(string key,T t,bool expired=true)
{
bool q=false;
if (expired)
{
q = client.Set(key, t,DateTime.Now.AddDays(ExpiredTime));
}
else
{
q = client.Set(key, t);
}
return q;
}
/// <summary>
/// 清空缓存
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
public virtual bool Remove(string key)
{
return client.Remove(key);
}
/// <summary>
/// 清空所有缓存
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
public virtual void FlushAll()
{
client.FlushAll();
}
/// <summary>
/// 获取所有key
/// </summary>
public virtual List<string> GetAllKeys()
{
var q = client.GetAllKeys();
return q;
}
/// <summary>
/// 获取所有键值对
/// </summary>
/// <param name="keys"></param>
/// <returns></returns>
public virtual IDictionary<string, T> GetAll(List<string> keys)
{
IDictionary<string, T> dict = client.GetAll<T>(keys);
return dict;
}
#endregion
}
然后创建接口
IDAL
namespace IDAL
{
public interface IBaseRepositoryRedis<T>
{
/// <summary>
/// 添加
/// </summary>
/// <param name="entity">数据实体</param>
/// <returns>添加后的数据实体</returns>
T Add(T entity, bool hasRedis = true);
/// <summary>
/// 添加
/// </summary>
/// <param name="entity">数据实体</param>
/// <returns>添加后的数据实体</returns>
bool AddOK(T entity, bool hasRedis = true);
/// <summary>
/// 查询记录数
/// </summary>
/// <param name="predicate">条件表达式</param>
/// <returns>记录数</returns>
int Count(Expression<Func<T, bool>> predicate, bool hasRedis = true);
/// <summary>
/// 更新
/// </summary>
/// <param name="entity">数据实体</param>
/// <returns>是否成功</returns>
T Update(T entity, bool hasRedis = true);
/// <summary>
/// 更新
/// </summary>
/// <param name="entity">数据实体</param>
/// <returns>是否成功</returns>
bool UpdateOK(T entity, bool hasRedis = true);
/// <summary>
/// 删除
/// </summary>
/// <param name="entity">数据实体</param>
/// <returns>是否成功</returns>
bool Delete(T entity, bool hasRedis = true);
/// <summary>
/// 是否存在
/// </summary>
/// <param name="anyLambda">查询表达式</param>
/// <returns>布尔值</returns>
bool Exist(Expression<Func<T, bool>> anyLambda, bool hasRedis = true);
/// <summary>
/// 查询数据
/// </summary>
/// <param name="whereLambda">查询表达式</param>
/// <returns>实体</returns>
T Find(Expression<Func<T, bool>> whereLambda, bool hasRedis = true);
/// <summary>
/// 查找数据列表
/// </summary>
/// <typeparam name="S">排序</typeparam>
/// <param name="whereLamdba">查询表达式</param>
/// <returns></returns>
List<T> FindList(Expression<Func<T, bool>> whereLamdba, bool hasRedis = true);
/// <summary>
/// 查找数据列表
/// </summary>
/// <typeparam name="S">排序</typeparam>
/// <param name="whereLamdba">查询表达式</param>
/// <param name="isAsc">是否升序</param>
/// <param name="orderLamdba">排序表达式</param>
/// <returns></returns>
List<T> FindList<S>(Expression<Func<T, bool>> whereLamdba, bool isAsc, Expression<Func<T, S>> orderLamdba, bool hasRedis = true);
/// <summary>
/// 查找分页数据列表
/// </summary>
/// <typeparam name="S">排序</typeparam>
/// <param name="pageIndex">当前页</param>
/// <param name="pageSize">每页记录数</param>
/// <param name="totalRecord">总记录数</param>
/// <param name="whereLamdba">查询表达式</param>
/// <param name="isAsc">是否升序</param>
/// <param name="orderLamdba">排序表达式</param>
/// <returns></returns>
List<T> FindPageList<S>(int pageIndex, int pageSize, out int totalRecord, Expression<Func<T, bool>> whereLamdba, bool isAsc, Expression<Func<T, S>> orderLamdba, bool hasRedis = true);
List<T> FindListBySQL<T>(string sql, params object[] parameters);
int ExecuteBySQL(string sql, params object[] parameters);
}
}
IBLL
namespace IBLL
{
public interface IBaseRepositoryRedisBLL<T> where T : class
{
/// <summary>
/// 添加
/// </summary>
/// <param name="entity">数据实体</param>
/// <returns>添加后的数据实体</returns>
T Add(T entity, bool hasRedis = true);
/// <summary>
/// 添加
/// </summary>
/// <param name="entity">数据实体</param>
/// <returns>添加后的数据实体</returns>
bool AddOK(T entity, bool hasRedis = true);
/// <summary>
/// 查询记录数
/// </summary>
/// <param name="predicate">条件表达式</param>
/// <returns>记录数</returns>
int Count(Expression<Func<T, bool>> predicate, bool hasRedis = true);
/// <summary>
/// 更新
/// </summary>
/// <param name="entity">数据实体</param>
/// <returns>是否成功</returns>
T Update(T entity, bool hasRedis = true);
/// <summary>
/// 更新
/// </summary>
/// <param name="entity">数据实体</param>
/// <returns>是否成功</returns>
bool UpdateOK(T entity, bool hasRedis = true);
/// <summary>
/// 删除
/// </summary>
/// <param name="entity">数据实体</param>
/// <returns>是否成功</returns>
bool Delete(T entity, bool hasRedis = true);
/// <summary>
/// 是否存在
/// </summary>
/// <param name="anyLambda">查询表达式</param>
/// <returns>布尔值</returns>
bool Exist(Expression<Func<T, bool>> anyLambda, bool hasRedis = true);
/// <summary>
/// 查询数据
/// </summary>
/// <param name="whereLambda">查询表达式</param>
/// <returns>实体</returns>
T Find(Expression<Func<T, bool>> whereLambda, bool hasRedis = true);
/// <summary>
/// 查找数据列表
/// </summary>
/// <typeparam name="S">排序</typeparam>
/// <param name="whereLamdba">查询表达式</param>
/// <returns></returns>
List<T> FindList(Expression<Func<T, bool>> whereLamdba, bool hasRedis = true);
/// <summary>
/// 查找数据列表
/// </summary>
/// <typeparam name="S">排序</typeparam>
/// <param name="whereLamdba">查询表达式</param>
/// <param name="isAsc">是否升序</param>
/// <param name="orderLamdba">排序表达式</param>
/// <returns></returns>
List<T> FindList<S>(Expression<Func<T, bool>> whereLamdba, bool isAsc, Expression<Func<T, S>> orderLamdba, bool hasRedis = true);
/// <summary>
/// 查找分页数据列表
/// </summary>
/// <typeparam name="S">排序</typeparam>
/// <param name="pageIndex">当前页</param>
/// <param name="pageSize">每页记录数</param>
/// <param name="totalRecord">总记录数</param>
/// <param name="whereLamdba">查询表达式</param>
/// <param name="isAsc">是否升序</param>
/// <param name="orderLamdba">排序表达式</param>
/// <returns></returns>
List<T> FindPageList<S>(int pageIndex, int pageSize, out int totalRecord, Expression<Func<T, bool>> whereLamdba, bool isAsc, Expression<Func<T, S>> orderLamdba, bool hasRedis = true);
List<T> FindListBySQL<T>(string sql, params object[] parameters);
int ExecuteBySQL(string sql, params object[] parameters);
}
}
DAL
这里,我们创建 BaseRepositoryRedis
namespace DAL.Base
{
public class BaseRepositoryRedis<T> : BaseClass, IBaseRepositoryRedis<T> where T : class
{
public ELDBEntity dbEF = DbContextFactory.GetCurrentContext();
RedisBLL<T> redis = new RedisBLL<T>();
public virtual T Add(T entity,bool hasRedis=true)
{
dbEF.Entry<T>(entity).State = EntityState.Added;
dbEF.SaveChanges();
if (hasRedis)
{
var q = SaveRedis();
}
return entity;
}
public virtual bool AddOK(T entity, bool hasRedis = true)
{
dbEF.Entry<T>(entity).State = EntityState.Added;
int count = dbEF.SaveChanges();
if (hasRedis)
{
var q = SaveRedis();
}
return count > 0;
}
public virtual int Count(Expression<Func<T, bool>> predicate, bool hasRedis = true)
{
List<T> q = new List<T>();
if (hasRedis)
{
var s = redis.Get<string>(typeof(T).ToString());
if (string.IsNullOrEmpty(s))
{
q = SaveRedis();
}
else
{
q = JsonConvert.DeserializeObject<List<T>>(s);
}
return q.Count(predicate.Compile());
}
return dbEF.Set<T>().AsNoTracking().Count(predicate);
}
public virtual T Update(T entity, bool hasRedis = true)
{
dbEF.Set<T>().Attach(entity);
dbEF.Entry<T>(entity).State = EntityState.Modified;
dbEF.SaveChanges();
if (hasRedis)
{
var q = SaveRedis();
}
return entity;
}
public virtual bool UpdateOK(T entity, bool hasRedis = true)
{
dbEF.Set<T>().Attach(entity);
dbEF.Entry<T>(entity).State = EntityState.Modified;
int count = dbEF.SaveChanges();
if (hasRedis)
{
var q = SaveRedis();
}
return count>0;
}
public virtual bool Delete(T entity, bool hasRedis = true)
{
dbEF.Set<T>().Attach(entity);
dbEF.Entry<T>(entity).State = EntityState.Deleted;
int count = dbEF.SaveChanges();
if (hasRedis)
{
var q = SaveRedis();
}
return count > 0;
}
public virtual bool Exist(Expression<Func<T, bool>> anyLambda, bool hasRedis = true)
{
List<T> q = new List<T>();
if (hasRedis)
{
var s = redis.Get<string>(typeof(T).ToString());
if (string.IsNullOrEmpty(s))
{
q = SaveRedis();
}
else
{
q = JsonConvert.DeserializeObject<List<T>>(s);
}
return q.Exists(anyLambda.Compile().ToPredicate());
}
return dbEF.Set<T>().AsNoTracking().Any(anyLambda);
}
public virtual T Find(Expression<Func<T, bool>> whereLambda, bool hasRedis = true)
{
List<T> q = new List<T>();
if (hasRedis)
{
var s = redis.Get<string>(typeof(T).ToString());
if (string.IsNullOrEmpty(s))
{
q = SaveRedis();
}
else
{
q = JsonConvert.DeserializeObject<List<T>>(s);
}
return q.Find(whereLambda.Compile().ToPredicate());
}
T _entity = dbEF.Set<T>().AsNoTracking().FirstOrDefault<T>(whereLambda);
return _entity;
}
public virtual List<T> FindList(Expression<Func<T, bool>> whereLamdba, bool hasRedis = true)
{
List<T> q = new List<T>();
if (hasRedis)
{
var s = redis.Get<string>(typeof(T).ToString());
if (string.IsNullOrEmpty(s))
{
q = SaveRedis();
}
else
{
q = JsonConvert.DeserializeObject<List<T>>(s);
}
}
else
{
q = dbEF.Set<T>().AsNoTracking().Where<T>(whereLamdba).ToList();
}
return q.FindAll(whereLamdba.Compile().ToPredicate());;
}
public virtual List<T> FindList<S>(Expression<Func<T, bool>> whereLamdba, bool isAsc, Expression<Func<T, S>> orderLamdba, bool hasRedis = true)
{
List<T> q = new List<T>();
if (hasRedis)
{
var s = redis.Get<string>(typeof(T).ToString());
if (string.IsNullOrEmpty(s))
{
q = SaveRedis();
}
else
{
q = JsonConvert.DeserializeObject<List<T>>(s);
}
q = q.FindAll(whereLamdba.Compile().ToPredicate());
}
else
{
q=dbEF.Set<T>().AsNoTracking().Where<T>(whereLamdba).ToList();
}
if (isAsc) q = q.OrderBy<T, S>(orderLamdba.Compile()).ToList();
else q = q.OrderByDescending<T, S>(orderLamdba.Compile()).ToList();
return q;
}
public virtual List<T> FindPageList<S>(int pageIndex, int pageSize, out int totalRecord, Expression<Func<T, bool>> whereLamdba, bool isAsc, Expression<Func<T, S>> orderLamdba, bool hasRedis = true)
{
List<T> q = new List<T>();
if (hasRedis)
{
var s = redis.Get<string>(typeof(T).ToString());
if (string.IsNullOrEmpty(s))
{
q = SaveRedis();
}
else
{
q = JsonConvert.DeserializeObject<List<T>>(s);
}
q = q.FindAll(whereLamdba.Compile().ToPredicate());
}
else
{
q = dbEF.Set<T>().AsNoTracking().Where<T>(whereLamdba).ToList();
}
totalRecord = q.Count();
if (isAsc) q = q.OrderBy<T, S>(orderLamdba.Compile()).Skip<T>((pageIndex - 1) * pageSize).Take<T>(pageSize).ToList();
else q = q.OrderByDescending<T, S>(orderLamdba.Compile()).Skip<T>((pageIndex - 1) * pageSize).Take<T>(pageSize).ToList();
return q;
}
public virtual PagedList<T> FindPageList1<S>(int pageIndex, int pageSize, out int totalRecord, Expression<Func<T, bool>> whereLamdba, bool isAsc, Expression<Func<T, S>> orderLamdba, bool hasRedis = true)
{
List<T> q = new List<T>();
if (hasRedis)
{
var s = redis.Get<string>(typeof(T).ToString());
if (string.IsNullOrEmpty(s))
{
q = SaveRedis();
}
else
{
q = JsonConvert.DeserializeObject<List<T>>(s);
}
q = q.FindAll(whereLamdba.Compile().ToPredicate());
}
else
{
q = dbEF.Set<T>().AsNoTracking().Where<T>(whereLamdba).ToList();
}
totalRecord = q.Count();
PagedList<T> resultList = null;
if (isAsc) resultList = q.OrderBy<T, S>(orderLamdba.Compile()).ToPagedList(pageIndex, pageSize);
else resultList = q.OrderByDescending<T, S>(orderLamdba.Compile()).ToPagedList(pageIndex, pageSize);
return resultList;
}
public virtual List<T> FindListBySQL<T>(string sql, params object[] parameters)
{
var list = dbEF.Database.SqlQuery<T>(sql, parameters).ToList();
return list;
}
public virtual int ExecuteBySQL(string sql, params object[] parameters)
{
var q = dbEF.Database.ExecuteSqlCommand(sql, parameters);
return q;
}
private List<T> SaveRedis()
{
List<T> q = dbEF.Set<T>().AsNoTracking().ToList();
var json = JsonConvert.SerializeObject(q);
redis.Set<string>(typeof(T).Name, json);
return q;
}
}
}
PS:说一下,为何要用json存储? 其实我也很无奈(Redis 无法保存ef复杂对象),看链接:http://blog.csdn.net/hanjun0612/article/details/54409892
BLL
namespace BLL.Base
{
public class BaseRepositoryRedisBLL<T> : BaseClass, IBaseRepositoryRedisBLL<T> where T : class
{
BaseRepositoryRedis<T> obj = new BaseRepositoryRedis<T>();
public virtual T Add(T entity, bool hasRedis = true)
{
return obj.Add(entity);
}
public virtual bool AddOK(T entity, bool hasRedis = true)
{
return obj.AddOK(entity);
}
public virtual int Count(System.Linq.Expressions.Expression<Func<T, bool>> predicate, bool hasRedis = true)
{
return obj.Count(predicate);
}
public virtual T Update(T entity, bool hasRedis = true)
{
return obj.Update(entity);
}
public virtual bool UpdateOK(T entity, bool hasRedis = true)
{
return obj.UpdateOK(entity);
}
public virtual bool Delete(T entity, bool hasRedis = true)
{
return obj.Delete(entity);
}
public virtual bool Exist(System.Linq.Expressions.Expression<Func<T, bool>> anyLambda, bool hasRedis = true)
{
return obj.Exist(anyLambda);
}
public virtual T Find(Expression<Func<T, bool>> whereLambda, bool hasRedis = true)
{
return obj.Find(whereLambda);
}
public virtual List<T> FindList(Expression<Func<T, bool>> whereLamdba, bool hasRedis = true)
{
var _list = obj.FindList(whereLamdba);
return _list;
}
public virtual List<T> FindList<S>(Expression<Func<T, bool>> whereLamdba, bool isAsc, System.Linq.Expressions.Expression<Func<T, S>> orderLamdba, bool hasRedis = true)
{
return obj.FindList<S>(whereLamdba, isAsc, orderLamdba);
}
public virtual List<T> FindPageList<S>(int pageIndex, int pageSize, out int totalRecord, Expression<Func<T, bool>> whereLamdba, bool isAsc, Expression<Func<T, S>> orderLamdba, bool hasRedis = true)
{
return obj.FindPageList<S>(pageIndex, pageSize, out totalRecord, whereLamdba, isAsc, orderLamdba);
}
public virtual PagedList<T> FindPageList1<S>(int pageIndex, int pageSize, out int totalRecord, Expression<Func<T, bool>> whereLamdba, bool isAsc, Expression<Func<T, S>> orderLamdba, bool hasRedis = true)
{
return obj.FindPageList1<S>(pageIndex, pageSize, out totalRecord, whereLamdba, isAsc, orderLamdba);
}
public virtual List<T> FindListBySQL<T>(string sql, params object[] parameters)
{
return obj.FindListBySQL<T>(sql, parameters);
}
public virtual int ExecuteBySQL(string sql, params object[] parameters)
{
return obj.ExecuteBySQL(sql, parameters);
}
}
}
最后,看一下用法
public class TestDAL : BaseRepositoryRedis<SYS_User>
{
//创建自定义方法
public string HelloWorld(string name)
{
return name + " Hello";
}
}
BLL
namespace BLL.Test
{
//继承BaseRepositoryBLL,拥有常用方法
public class TestBLL : BaseRepositoryRedisBLL<SYS_User>
{
}
}
ef 仓储模式 Redis的更多相关文章
- ef 仓储模式
构建一个仓储模式. Model 大家自己创建就行了,上个图,就不多说了(我是code first) IDAL namespace IDAL { public interface IBaseReposi ...
- MVC+EF 理解和实现仓储模式和工作单元模式
MVC+EF 理解和实现仓储模式和工作单元模式 原文:Understanding Repository and Unit of Work Pattern and Implementing Generi ...
- 用MVC5+EF6+WebApi 做一个考试功能(六) 仓储模式 打造EF通用仓储类
前言 年底工作比较忙,年度总结还没写,项目要上线,回老家过年各种准备.尤其是给长辈给侄子侄女准备礼物头都大了. 原来想年前先出一版能用的,我看有点悬了,尽量先把大体功能弄出来,扔掉一些,保证能考试,然 ...
- 6.在MVC中使用泛型仓储模式和依赖注入实现增删查改
原文链接:http://www.c-sharpcorner.com/UploadFile/3d39b4/crud-operations-using-the-generic-repository-pat ...
- 4.在MVC中使用仓储模式进行增删查改
原文链接:http://www.c-sharpcorner.com/UploadFile/3d39b4/crud-using-the-repository-pattern-in-mvc/ 系列目录: ...
- 5.在MVC中使用泛型仓储模式和工作单元来进行增删查改
原文链接:http://www.c-sharpcorner.com/UploadFile/3d39b4/crud-operations-using-the-generic-repository-pat ...
- ASP.NET Mvc实用框架(一)Ioc、仓储模式和单元工作模式
Framework.EF 首先看一下这个类库: Extended文件夹存放的是EntityFramework.Extensions这个插件的源代码,没有别的原因,就是本人觉得这个插件挺好的,每次省的下 ...
- MVC5+EF6 入门完整教程十一:细说MVC中仓储模式的应用
摘要: 第一阶段1~10篇已经覆盖了MVC开发必要的基本知识. 第二阶段11-20篇将会侧重于专题的讲解,一篇文章解决一个实际问题. 根据园友的反馈, 本篇文章将会先对呼声最高的仓储模式进行讲解. 文 ...
- MVC5+EF6 入门完整教程11--细说MVC中仓储模式的应用
摘要: 第一阶段1~10篇已经覆盖了MVC开发必要的基本知识. 第二阶段11-20篇将会侧重于专题的讲解,一篇文章解决一个实际问题. 根据园友的反馈, 本篇文章将会先对呼声最高的仓储模式进行讲解. 文 ...
随机推荐
- python wsgi 简介
wsgi全称是"Web Server Gateway Interfacfe",web服务器网关接口,wsgi在python2.5中加入,是web服务器和web应用的标准接口,任何实 ...
- oracle 相除后保留指定位数小数round()
) xxx from dual; XXX---------- 3.8871
- Redis详解(八)------ 主从复制
前面介绍Redis,我们都在一台服务器上进行操作的,也就是说读和写以及备份操作都是在一台Redis服务器上进行的,那么随着项目访问量的增加,对Redis服务器的操作也越加频繁,虽然Redis读写速度都 ...
- 在WPF中使用FontAwesome图标字体
原文:在WPF中使用FontAwesome图标字体 版权声明:原创内容转载必须注明出处,否则追究相关责任. https://blog.csdn.net/qq_36663276/article/deta ...
- C# DllImport 相对路径无法找到dll
原文:C# DllImport 相对路径无法找到dll 如题,近期在开发过程中,需要调用C++的库,一般来说,使用下面的方法即可正常调用: [DllImport("hci_sys.dll&q ...
- ubuntu在指定的文件夹下创建python3和python2的虚拟环境
1.用pip安装virtualenv sudo apt-get install python-virtualenv 2.创建python2和python3虚拟环境 2.1 创建python2的虚拟环境 ...
- gist.github.com 被墙无法访问解决办法
windows下 打开C:\Windows\System32\drivers\etc\hosts文件 编辑器打开,在最后行添加192.30.253.118 gist.github.com 保存.
- Object-Oriented(二)原型对象
自用备忘笔记 1. 理解原型对象 只要创建函数,函数上就会创建一个 prototype 属性指向函数的原型对象. function Person() {} Person.prototype //指向该 ...
- Mvc4_ @RenderBody、@RenderPage、@RenderSection用法
一.@RenderBody 当创建基于_Layout.cshtml布局页面的视图时,视图的内容会和布局页面合并,而新创建视图的内容会通过_Layout.cshtml布局页面的@RenderBody() ...
- Oracle_安装说明
1.先到Oracle官网上下载11g oracle Database 11g 第 2 版 (11.2.0.1.0) 标准版.标准版 1 以及企业版 适用于 Microsoft Windows (x64 ...