1.创建依赖的实体类

/// <summary>

/// 泛型实体基类
/// </summary>
/// <typeparam name="TPrimaryKey">主键类型</typeparam>
public abstract class Entity<TPrimaryKey>
{
/// <summary>
/// 主键
/// </summary>
public virtual TPrimaryKey Id { get; set; }
} /// <summary>
/// 定义默认主键类型为int的实体基类
/// </summary>
public abstract class Entitys : Entity<int>
{ }

2.定义封装的接口

public interface IRepository<T> where T : Entitys
{ //异步保存保存信息
Task<int> SaveChangesAsync();
void SaveChanges(); //添加实体类
T Add(T data); //批量添加实体类
IEnumerable<T> AddRange(IEnumerable<T> entitys); //异步批量添加实体类
Task<IEnumerable<T>> AddRangeAsync(IEnumerable<T> entitys); bool Remove(T data); bool RemoveRange(IEnumerable<T> entitys); bool Update(T data); int Max(Expression<Func<T, int>> whereLamdba); /// <summary>
/// 查询记录数
/// </summary>
/// <param name="whereLambda">查询表达式</param>
/// <returns></returns>
int Count(Expression<Func<T, bool>> whereLambda); /// <summary>
/// 是否存在
/// </summary>
/// <param name="anyLambda">查询表达式</param>
/// <returns></returns>
bool Exist(Expression<Func<T, bool>> anyLambda); /// <summary>
/// 得到数据集
/// </summary>
/// <returns></returns>
DbSet<T> Set(); T Find(Expression<Func<T, bool>> whereLambda); /// <summary>
/// 查找数据列表
/// </summary>
/// <param name="whereLamdba">查询表达式</param>
/// <param name="orderName">排序名称</param>
/// <param name="isAsc">isAsc</param>
/// <returns></returns>
IQueryable<T> FindList(Expression<Func<T, bool>> whereLamdba, string orderName, bool isAsc);
/// <summary>
/// sql查找数据列表
/// </summary>
/// <param name="sql"></param>
/// <param name="pageIndex"></param>
/// <param name="pageSize"></param>
/// <param name="totalRecord"></param>
/// <param name="whereLamdba"></param>
/// <param name="orderName"></param>
/// <param name="isAsc"></param>
/// <returns></returns>
IQueryable<T> FindPageListFromsql(int pageIndex, int pageSize, out int totalRecord, string sql, string orderName, bool isAsc);
/// <summary>
/// 查找分页数据列表
/// </summary>
/// <param name="pageIndex">当前页</param>
/// <param name="pageSize">每页记录数</param>
/// <param name="totalRecord">总记录数</param>
/// <param name="whereLamdba">查询表达式</param>
/// <param name="orderName">排序名称</param>
/// <param name="isAsc">是否升序</param>
/// <returns></returns>
IQueryable<T> FindPageList(int pageIndex, int pageSize, out int totalRecord, Expression<Func<T, bool>> whereLamdba, string orderName, bool isAsc); IQueryable<T> FromSql(string sql); /// <summary>
/// 操作数据库
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
int ExecuteSqlCommand(string sql);
}

3 .实现接口方法

public class Repository<T> : IRepository<T> where T : Entitys
{
protected virtual StudyDbContext nWriteContext { get; set; }
protected virtual StudyDbContext nReadContext { get; set; } public Repository(IServiceProvider serviceProvider, StudyDbContext studyDbContext)
{
this.nWriteContext = studyDbContext;
this.nReadContext = this.nWriteContext;
} public void SaveChanges()
{
nWriteContext.SaveChanges();
}
public async Task<int> SaveChangesAsync()
{
return await nWriteContext.SaveChangesAsync();
} public T Add(T entity)
{
nWriteContext.Entry<T>(entity).State = EntityState.Added;
nWriteContext.SaveChanges();
return entity;
} public IEnumerable<T> AddRange(IEnumerable<T> entitys)
{
foreach (var entity in entitys)
{
nWriteContext.Entry<T>(entity).State = EntityState.Added;
}
nWriteContext.SaveChanges();
return entitys;
}
public async Task<IEnumerable<T>> AddRangeAsync(IEnumerable<T> entitys)
{
foreach (var entity in entitys)
{
nWriteContext.Entry<T>(entity).State = EntityState.Added;
}
await nWriteContext.SaveChangesAsync();
return entitys;
} public int Count(Expression<Func<T, bool>> predicate)
{
//return nReadContext.Set<T>().Count(predicate);
return nReadContext.Set<T>().Count(predicate);
} public bool Update(T entity)
{
nWriteContext.Set<T>().Attach(entity);
nWriteContext.Entry<T>(entity).State = EntityState.Modified;
return nWriteContext.SaveChanges() > ;
} public bool Remove(T entity)
{
nWriteContext.Set<T>().Attach(entity);
nWriteContext.Entry<T>(entity).State = EntityState.Deleted;
return nWriteContext.SaveChanges() > ;
} public bool RemoveRange(IEnumerable<T> entitys)
{
foreach (var entity in entitys)
{
nWriteContext.Set<T>().Attach(entity);
nWriteContext.Entry<T>(entity).State = EntityState.Deleted;
}
return nWriteContext.SaveChanges() > ;
} public bool Exist(Expression<Func<T, bool>> anyLambda)
{
return nReadContext.Set<T>().Any(anyLambda); //Read
} public T Find(Expression<Func<T, bool>> whereLambda)
{
T _entity = nReadContext.Set<T>().FirstOrDefault<T>(whereLambda);//Read
return _entity;
} public DbSet<T> Set()
{
//var type = DbSlaveType.master;
//if (type == DbSlaveType.master)
//{
return nWriteContext.Set<T>();
//}
//else
//{
// return nReadContext.Set<T>();//read
//}
} public IQueryable<T> FindList(Expression<Func<T, bool>> whereLamdba, string orderName, bool isAsc)
{
var _list = nReadContext.Set<T>().Where<T>(whereLamdba); //read
_list = OrderBy(_list, orderName, isAsc);
return _list;
} public IQueryable<T> FindPageList(int pageIndex, int pageSize, out int totalRecord, Expression<Func<T, bool>> whereLamdba, string orderName, bool isAsc)
{
var _list = nReadContext.Set<T>().Where<T>(whereLamdba); //read
totalRecord = _list.Count();
_list = OrderBy(_list, orderName, isAsc).Skip<T>((pageIndex - ) * pageSize).Take<T>(pageSize);
return _list;
} public IQueryable<T> FindPageListFromsql(int pageIndex, int pageSize, out int totalRecord, string sql, string orderName, bool isAsc)
{
var _list = nWriteContext.Set<T>().FromSql(sql); //read
totalRecord = _list.Count();
_list = OrderBy(_list, orderName, isAsc).Skip<T>((pageIndex - ) * pageSize).Take<T>(pageSize);
return _list;
}
/// <summary>
/// 排序
/// </summary>
/// <typeparam name="T">类型</typeparam>
/// <param name="source">原IQueryable</param>
/// <param name="propertyName">排序属性名</param>
/// <param name="isAsc">是否正序</param>
/// <returns>排序后的IQueryable<T></returns>
private IQueryable<T> OrderBy(IQueryable<T> source, string propertyName, bool isAsc)
{
if (source == null)
{
//throw new ArgumentNullException("source", "不能为空");
return null;
}
if (string.IsNullOrEmpty(propertyName)) return source;
var _parameter = Expression.Parameter(source.ElementType);
var _property = Expression.Property(_parameter, propertyName);
if (_property == null)
{
// throw new ArgumentNullException("propertyName", "属性不存在");
return null;
}
var _lambda = Expression.Lambda(_property, _parameter);
var _methodName = isAsc ? "OrderBy" : "OrderByDescending";
var _resultExpression = Expression.Call(typeof(Queryable), _methodName, new Type[] { source.ElementType, _property.Type }, source.Expression, Expression.Quote(_lambda));
return source.Provider.CreateQuery<T>(_resultExpression);
} public int Max(Expression<Func<T, int>> whereLamdba)
{
return nWriteContext.Set<T>().Select(whereLamdba).Max(); //read
} public IQueryable<T> FromSql(string sql)
{
return nWriteContext.Set<T>().FromSql(sql); //read
} public int ExecuteSqlCommand(string sql)
{
return nWriteContext.Database.ExecuteSqlCommand(sql);
} }

Repository封装方法的更多相关文章

  1. js面向对象的封装方法,【案例】

    封装方法: /** * @矩形canvas库 * @authors Shimily (275766400@qq.com) * @date 2016-12-28 10:30:51 * @version ...

  2. Javascript 封装方法

    基本封装方法 请看下面的例子: var Person = function(name,age){ this.name = name; this.age = age || "未填写" ...

  3. [论文笔记] 一种Java遗留系统服务化切分和封装方法 (计算机学报, 2009)

    李翔,怀进鹏,曾晋,高鹏. 一种Java遗留系统服务化切分和封装方法. 计算机学报, 32(9), 2009, p1084-1815 (gs:5) 1. 本文研究从Java遗留系统中切分并封装出Web ...

  4. 分享几个Javascript 封装方法

    基本封装方法 请看下面的例子: var Person = function(name,age){ this.name = name; this.age = age || "未填写" ...

  5. iOS常用的封装方法

    做开发也有一段时间了,看了好多大神的代码,总体感觉他们写的代码简洁,好看,然而在对比下我写的代码,混乱,无序,简直不堪入目啊! 总体来说大神们的代码封装的都比较好,对一个项目要重复用到的代码他们都会封 ...

  6. JavaScrpt常用的封装方法

    1.闭包封装.在这个封装方法中,所有的实例成员都共享属性和方法, 使得所有得方法和属性都私有且对象间共享 (function ($) { var Person = function(name) { r ...

  7. Lua常用封装方法

    Lua 获取随机值 --获取随机值,指定上限和下限 function getRandom(min,max) -- 接收一个整数n作为随即序列的种子 math.randomseed(os.time()) ...

  8. MP实战系列(十二)之封装方法详解(续二)

    继续MP实战系列(十一)之封装方法详解(续一)这篇文章之后. 此次要讲的是关于查询. 查询是用的比较多的,查询很重要,好的查询,加上索引如鱼得水,不好的查询加再多索引也是无济于事. 1.selectB ...

  9. MP实战系列(十一)之封装方法详解(续一)

    之前写的封装方法详解,比较简要. 今天我主要讲增加和删除及其修改.查的话得单独再详讲. 增删改查,无论是Java或者C#等等,凡是对数据库操作的都离不开这四个. 一.增加方法讲解 MyBatis Pl ...

随机推荐

  1. 全网最通俗易懂的Kafka入门!

    前言 只有光头才能变强. 文本已收录至我的GitHub仓库,欢迎Star:https://github.com/ZhongFuCheng3y/3y 在这篇之前已经写过两篇基础文章了,强烈建议先去阅读: ...

  2. 05-kubernetes Pod控制器应用进阶

    目录 Pod 资源 标签 给资源打标签 标签选择器 Pod 生命周期 实际操作 livenessProbe 实战 livenessProbe exec 测试 livenessProbe httpGet ...

  3. php-fpm的pool、php-fpm慢执行日志、open_basedir、php-fpm进程管理

    6月13日任务 12.21 php-fpm的pool12.22 php-fpm慢执行日志12.23 open_basedir12.24 php-fpm进程管理 12.21 php-fpm的pool p ...

  4. [TimLinux] Python 迭代器(iterator)和生成器(generator)

    1. 可迭代对象 from collection import Iterable class Iterable(metaclass=ABCMeta): ... def __iter__(self): ...

  5. HDU2242 考研路茫茫——空调教室 (双联通分+树形DP)

    考研路茫茫——空调教室 Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Total ...

  6. POJ 3041 Asteroids(二分图模板题)

    Bessie wants to navigate her spaceship through a dangerous asteroid field in the shape of an N x N g ...

  7. tensorflow tf.train.Supervisor作用

    tf.train.Supervisor可以简化编程,避免显示地实现restore操作.通过一个例子看. import tensorflow as tf import numpy as np impor ...

  8. .net core 如何正确的读取body中的内容

    private string BodyToJson() { var reader = new StreamReader(Request.Body); var contentFromBody = rea ...

  9. art-template模板判断

    1.添加模板 <script id="userinfo" type="text/template">           {{ if id == n ...

  10. linux-history、find、

    1.history:查看历史记录 -c:清除历史命令记录 -d:删除某一条使用过的命令,-d后跟命令的序列号 2.find:在目录结构中搜索文件 -type:后面跟文件的类型,d表示目录,f表示文件 ...