using System;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using System.Linq.Expressions;
using YunEdu.Model; namespace DAL
{
/// <summary>
/// EF数据库操作基类
/// </summary>
/// <typeparam name="T"></typeparam>
public partial class BaseDAL<T> where T : class, new()
{
/// <summary>
/// 数据库上下文
/// </summary>
private DbContext dbContext = DbContextFactory.Create(); /*
* 2017-03-22 重新封装的方法
* 2017-03-26 更新方法添加异步
*/ #region Add 添加实体 /// <summary>
/// 添加
/// </summary>
/// <param name="entity">实体</param>
/// <param name="isSave">是否立即保存</param>
/// <returns>添加的记录数[isSave=true时有效]</returns>
public virtual int Add(T entity, bool isSave = true)
{
dbContext.Set<T>().Add(entity);
if (isSave) return dbContext.SaveChanges();
else return ;
} /// <summary>
/// 添加(异步)
/// </summary>
/// <param name="entity">实体</param>
/// <param name="isSave">是否立即保存</param>
/// <returns>添加的记录数[isSave=true时有效]</returns>
public virtual async Task<int> AddAsync(T entity, bool isSave = true)
{
dbContext.Set<T>().Add(entity);
if (isSave) return await dbContext.SaveChangesAsync();
else return ;
} /// <summary>
/// 添加[批量]
/// </summary>
/// <param name="entities">实体</param>
/// <param name="isSave">是否立即保存</param>
/// <returns>添加的记录数[isSave=true时有效]</returns>
public virtual int AddRange(T[] entities, bool isSave = true)
{
dbContext.Set<T>().AddRange(entities);
if (isSave) return dbContext.SaveChanges();
else return ;
} /// <summary>
/// 添加[批量](异步)
/// </summary>
/// <param name="entities">实体</param>
/// <param name="isSave">是否立即保存</param>
/// <returns>添加的记录数[isSave=true时有效]</returns>
public virtual async Task<int> AddRangeAsync(T[] entities, bool isSave = true)
{
dbContext.Set<T>().AddRange(entities);
if (isSave) return await dbContext.SaveChangesAsync();
else return ;
} #endregion #region Delete 删除实体 /// <summary>
/// 删除
/// </summary>
/// <param name="entity">实体</param>
/// <param name="isSave">是否立即保存</param>
/// <returns>是否删除成功[isSave=true时有效]</returns>
public virtual bool Remove(T entity, bool isSave = true)
{
dbContext.Set<T>().Remove(entity);
if (isSave) return dbContext.SaveChanges() > ;
else return false;
} /// <summary>
/// 删除(异步)
/// </summary>
/// <param name="entity">实体</param>
/// <param name="isSave">是否立即保存</param>
/// <returns>是否删除成功[isSave=true时有效]</returns>
public virtual async Task<bool> RemoveAsync(T entity, bool isSave = true)
{
dbContext.Set<T>().Remove(entity);
if (isSave) return await dbContext.SaveChangesAsync() > ;
else return false;
} /// <summary>
/// 批量删除
/// </summary>
/// <param name="entities">实体数组</param>
/// <param name="isSave">是否立即保存</param>
/// <returns>成功删除的记录数</returns>
public virtual int RemoveRange(T[] entities, bool isSave = true)
{
dbContext.Set<T>().RemoveRange(entities);
if (isSave) return dbContext.SaveChanges();
else return ;
} /// <summary>
/// 批量删除(异步)
/// </summary>
/// <param name="entities">实体数组</param>
/// <param name="isSave">是否立即保存</param>
/// <returns>成功删除的记录数[isSave=true时有效]</returns>
public virtual async Task<int> RemoveRangeAsync(T[] entities, bool isSave = true)
{
dbContext.Set<T>().RemoveRange(entities);
if (isSave) return await dbContext.SaveChangesAsync();
else return ;
} #endregion #region Update 更新实体 /// <summary>
/// 更新实体
/// </summary>
/// <param name="entity">实体</param>
/// <param name="isSave">是否立即保存</param>
/// <returns>在“isSave”为True时返回受影响的对象的数目,为False时直接返回0</returns>
public virtual int Update(T entity, bool isSave)
{
dbContext.Set<T>().Attach(entity);
dbContext.Entry<T>(entity).State = EntityState.Modified;//将所有属性标记为修改状态
return isSave ? dbContext.SaveChanges() : ;
} /// <summary>
/// 更新实体(异步)
/// </summary>
/// <param name="entity">实体</param>
/// <param name="isSave">是否立即保存</param>
/// <returns>在“isSave”为True时返回受影响的对象的数目,为False时直接返回0</returns>
public async virtual Task<int> UpdateAsync(T entity, bool isSave)
{
dbContext.Set<T>().Attach(entity);
dbContext.Entry<T>(entity).State = EntityState.Modified;//将所有属性标记为修改状态
if (isSave) return await dbContext.SaveChangesAsync();
return ;
} #endregion #region Find 查询实体
/// <summary>
/// 查找最大实体
/// </summary>
/// <returns></returns>
public virtual T Max()
{
return dbContext.Set<T>().Max();
} /// <summary>
/// 查找最大实体(异步)
/// </summary>
/// <returns></returns>
public async virtual Task<T> MaxAsync()
{
return await dbContext.Set<T>().MaxAsync();
} /// <summary>
/// 查找实体(根据主键值查找)
/// </summary>
/// <param name="ID">实体主键值</param>
/// <returns></returns>
public virtual T Find(int ID)
{
return dbContext.Set<T>().Find(ID);
} /// <summary>
/// 查找实体(根据主键值查找,异步)
/// </summary>
/// <param name="ID">实体主键值</param>
/// <returns></returns>
public async virtual Task<T> FindAsync(int ID)
{
return await dbContext.Set<T>().FindAsync(ID);
} /// <summary>
/// 查找(根据联合主键)
/// </summary>
/// <param name="keyValues">主键</param>
/// <returns></returns>
public virtual T Find(object[] keyValues)
{
return dbContext.Set<T>().Find(keyValues);
} /// <summary>
/// 查找(根据联合主键,异步)
/// </summary>
/// <param name="keyValues">主键</param>
/// <returns></returns>
public virtual async Task<T> FindAsync(object[] keyValues)
{
return await dbContext.Set<T>().FindAsync(keyValues);
} /// <summary>
/// 查找实体(根据Lambda表达式)
/// </summary>
/// <param name="where">查询Lambda表达式</param>
/// <returns></returns>
public virtual T FindSingle(Expression<Func<T, bool>> where)
{
return dbContext.Set<T>().SingleOrDefault(where);
} /// <summary>
/// 查找实体(根据Lambda表达式,异步)
/// </summary>
/// <param name="where">查询Lambda表达式</param>
/// <returns></returns>
public async virtual Task<T> FindSingleAsync(Expression<Func<T, bool>> where)
{
return await dbContext.Set<T>().SingleOrDefaultAsync(where);
}
#endregion #region List 查询列表 /// <summary>
/// 查询所有
/// </summary>
/// <returns></returns>
public virtual IQueryable<T> FindList()
{
return dbContext.Set<T>();
} /// <summary>
/// 查询所有(异步)
/// </summary>
/// <returns>实体列表</returns>
public virtual async Task<IQueryable<T>> FindListAsync()
{
IQueryable<T> result = dbContext.Set<T>();
return await Task.FromResult(result);
} /// <summary>
/// 查询(根据查询条件)
/// </summary>
/// <param name="predicate">查询条件</param>
/// <returns>实体列表</returns>
public virtual IQueryable<T> FindList(Expression<Func<T, bool>> predicate)
{
return dbContext.Set<T>().Where(predicate);
} /// <summary>
/// 查询(根据查询条件,异步)
/// </summary>
/// <param name="predicate">查询条件</param>
/// <returns>实体列表</returns>
public virtual async Task<IQueryable<T>> FindListAsync(Expression<Func<T, bool>> predicate)
{
return await Task.FromResult(FindList(predicate));
} /// <summary>
/// 查询(前几条)数据(根据查询条件)
/// </summary>
/// <param name="number">返回记录数</param>
/// <param name="predicate">查询条件</param>
/// <returns>实体列表</returns>
public virtual IQueryable<T> FindList(int number, Expression<Func<T, bool>> predicate)
{
var entityList = dbContext.Set<T>().Where(predicate);
if (number > ) return entityList.Take(number);
else return entityList;
} /// <summary>
/// 查询(前几条)数据(根据查询条件,异步)
/// </summary>
/// <param name="number">返回记录数</param>
/// <param name="predicate">查询条件</param>
/// <returns>实体列表</returns>
public virtual async Task<IQueryable<T>> FindListAsync(int number, Expression<Func<T, bool>> predicate)
{
return await Task.FromResult(FindList(number, predicate));
} /// <summary>
/// 查询(前几条)数据(根据查询条件,带排序)
/// </summary>
/// <param name="number">显示数量[小于等于0-不启用]</param>
/// <typeparam name="TKey">排序字段</typeparam>
/// <param name="predicate">查询条件</param>
/// <param name="keySelector">排序</param>
/// <param name="isAsc">正序</param>
/// <returns></returns>
public virtual IQueryable<T> FindList<TKey>(int number, Expression<Func<T, bool>> predicate, Expression<Func<T, TKey>> keySelector, bool isAsc)
{
var entityList = dbContext.Set<T>().Where(predicate);
if (isAsc) entityList = entityList.OrderBy(keySelector);
else entityList.OrderByDescending(keySelector);
if (number > ) return entityList.Take(number);
else return entityList;
} /// <summary>
/// 查询(前几条)数据(根据查询条件,带排序,异步)
/// </summary>
/// <param name="number">显示数量[小于等于0-不启用]</param>
/// <typeparam name="TKey">排序字段</typeparam>
/// <param name="predicate">查询条件</param>
/// <param name="keySelector">排序</param>
/// <param name="isAsc">正序</param>
/// <returns></returns>
public virtual async Task<IQueryable<T>> FindListAsync<TKey>(int number, Expression<Func<T, bool>> predicate, Expression<Func<T, TKey>> keySelector, bool isAsc)
{
var entityList = dbContext.Set<T>().Where(predicate);
if (isAsc) entityList = entityList.OrderBy(keySelector);
else entityList.OrderByDescending(keySelector);
if (number > ) entityList = entityList.Take(number);
return await Task.FromResult(entityList);
} #endregion #region Count 查询总数 /// <summary>
/// 查询记录数
/// </summary>
/// <param name="predicate">查询条件表达式</param>
/// <returns>记录数</returns>
public virtual int Count(Expression<Func<T, bool>> predicate)
{
return dbContext.Set<T>().Count(predicate);
} /// <summary>
/// 查询记录数(异步)
/// </summary>
/// <param name="predicate">查询条件表达式</param>
/// <returns>记录数</returns>
public virtual async Task<int> CountAsync(Expression<Func<T, bool>> predicate)
{
return await dbContext.Set<T>().CountAsync(predicate);
} #endregion #region Exist 是否存在 /// <summary>
/// 查询是否存在
/// </summary>
/// <param name="predicate">查询条件表达式</param>
/// <returns>是否存在</returns>
public virtual bool Exists(Expression<Func<T, bool>> predicate)
{
return dbContext.Set<T>().Any(predicate);
} /// <summary>
/// 查询是否存在(异步)
/// </summary>
/// <param name="predicate">查询条件表达式</param>
/// <returns>是否存在</returns>
public virtual async Task<bool> ExistsAsync(Expression<Func<T, bool>> predicate)
{
return await dbContext.Set<T>().AnyAsync(predicate);
} #endregion #region Page 分页查询 /// <summary>
/// 查找分页列表(无条件,无排序)
/// </summary>
/// <param name="pageSize">每页记录数。必须大于1</param>
/// <param name="pageIndex">页码。首页从1开始,页码必须大于1</param>
/// <param name="totalNumber">总记录数</param>
/// <returns></returns>
public virtual IQueryable<T> FindPageList(int pageSize, int pageIndex, out int totalNumber)
{
OrderParam _orderParam = null;
return FindPageList(pageSize, pageIndex, out totalNumber, _orderParam);
} /// <summary>
/// 查找分页列表(无条件,带排序)
/// </summary>
/// <param name="pageSize">每页记录数。必须大于1</param>
/// <param name="pageIndex">页码。首页从1开始,页码必须大于1</param>
/// <param name="totalNumber">总记录数</param>
/// <param name="order">排序键</param>
/// <param name="asc">是否正序</param>
/// <returns></returns>
public virtual IQueryable<T> FindPageList(int pageSize, int pageIndex, out int totalNumber, OrderParam orderParam)
{
return FindPageList(pageSize, pageIndex, out totalNumber, (T) => true, orderParam);
} /// <summary>
/// 查找分页列表(带条件,无排序)
/// </summary>
/// <param name="pageSize">每页记录数。必须大于1</param>
/// <param name="pageIndex">页码。首页从1开始,页码必须大于1</param>
/// <param name="totalNumber">总记录数</param>
/// <param name="where">查询表达式</param>
public virtual IQueryable<T> FindPageList(int pageSize, int pageIndex, out int totalNumber, Expression<Func<T, bool>> where)
{
OrderParam _param = null;
return FindPageList(pageSize, pageIndex, out totalNumber, where, _param);
} /// <summary>
/// 查找分页列表(无条件,单字段排序)
/// </summary>
/// <param name="pageSize">每页记录数。</param>
/// <param name="pageIndex">页码。首页从1开始</param>
/// <param name="totalNumber">总记录数</param>
/// <param name="where">查询表达式</param>
/// <param name="orderParam">排序【null-不设置】</param>
/// <returns></returns>
public virtual IQueryable<T> FindPageList(int pageSize, int pageIndex, out int totalNumber, Expression<Func<T, bool>> where, OrderParam orderParam)
{
OrderParam[] _orderParams = null;
if (orderParam != null) _orderParams = new OrderParam[] { orderParam };
return FindPageList(pageSize, pageIndex, out totalNumber, where, _orderParams);
} /// <summary>
/// 查找分页列表(带条件,带多字段排序)
/// </summary>
/// <param name="pageSize">每页记录数。</param>
/// <param name="pageIndex">页码。首页从1开始</param>
/// <param name="totalNumber">总记录数</param>
/// <param name="where">查询表达式</param>
/// <param name="orderParams">排序【null-不设置】</param>
public virtual IQueryable<T> FindPageList(int pageSize, int pageIndex, out int totalNumber, Expression<Func<T, bool>> where, OrderParam[] orderParams)
{
//条件过滤
IQueryable<T> query = where == null ? dbContext.Set<T>() : dbContext.Set<T>().Where(where); //创建表达式变量参数
var parameter = Expression.Parameter(typeof(T), "o"); if (orderParams != null && orderParams.Length > )
{
for (int i = ; i < orderParams.Length; i++)
{
//根据属性名获取属性
var property = typeof(T).GetProperty(orderParams[i].PropertyName);
//创建一个访问属性的表达式
var propertyAccess = Expression.MakeMemberAccess(parameter, property);
var orderByExp = Expression.Lambda(propertyAccess, parameter); string OrderName = "";
if (i > )
{
OrderName = orderParams[i].IsDesc ? "ThenByDescending" : "ThenBy";
}
else
OrderName = orderParams[i].IsDesc ? "OrderByDescending" : "OrderBy"; MethodCallExpression resultExp = Expression.Call(typeof(Queryable), OrderName, new Type[] { typeof(T), property.PropertyType }, query.Expression, Expression.Quote(orderByExp)); query = query.Provider.CreateQuery<T>(resultExp);
}
} totalNumber = query.Count();
return query.Skip((pageIndex - ) * pageSize).Take(pageSize);
} /// <summary>
/// 查找分页列表(带条件,单字段lambda表达式排序)
/// </summary>
/// <typeparam name="type">排序字段类型</typeparam>
/// <param name="pageSize">每页记录数</param>
/// <param name="pageIndex">页码,首页从1开始</param>
/// <param name="totalNumber">输出总数</param>
/// <param name="isAsc">是否升序</param>
/// <param name="OrderByLambda">排序条件</param>
/// <param name="WhereLambda">查询条件</param>
/// <returns></returns>
public virtual IQueryable<T> FindPageList<type>(int pageSize, int pageIndex, out int totalNumber, bool isAsc,
Expression<Func<T, type>> OrderByLambda, Expression<Func<T, bool>> WhereLambda)
{
//输出记录总数
totalNumber = dbContext.Set<T>().Where(WhereLambda).Count();
//是否升序
if (isAsc)
{
return dbContext.Set<T>().Where(WhereLambda).OrderBy(OrderByLambda).Skip((pageIndex - ) * pageSize).Take(pageSize);
}
else
{
return dbContext.Set<T>().Where(WhereLambda).OrderByDescending(OrderByLambda).Skip((pageIndex - ) * pageSize).Take(pageSize);
}
}
#endregion #region Save 保存数据
/// <summary>
/// 保存数据【在Add、Upate、Delete未立即保存的情况下使用】
/// </summary>
/// <returns>更改的记录数</returns>
public virtual int SaveChanges()
{
return dbContext.SaveChanges();
} /// <summary>
/// 保存数据【在Add、Upate、Delete未立即保存的情况下使用】(异步)
/// </summary>
/// <returns>更改的记录数</returns>
public virtual async Task<int> SaveChangesAsync()
{
return await dbContext.SaveChangesAsync();
}
#endregion #region 扩展用 私有方法 /// <summary>
/// 私有方法,用于更新指定列
/// </summary>
/// <param name="entity">实体</param>
/// <param name="properties">要修改的属性名称</param>
private void UpdateRe(T entity, string[] properties = null)
{
var entry = dbContext.Entry(entity);
if (properties == null)
{
entry.State = EntityState.Modified;//将所有属性标记为修改状态
}
else
{
//Detached 对象存在,但未由对象服务跟踪。在创建实体之后、但将其添加到对象上下文之前,该实体处于此状态;
if (entry.State == EntityState.Detached) entry.State = EntityState.Unchanged;//先将所有属性状态标记为未修改
foreach (var property in properties)
{
entry.Property(property).IsModified = true;//将要修改的属性状态标记为修改
}
}
} #endregion }
}

BaseDAL最牛数据层基类2的更多相关文章

  1. BaseDAL数据层基类1

    /// <summary> /// EF数据库操作基类 /// </summary> /// <typeparam name="T"></ ...

  2. Hibernate 数据层基类实现

    提取经常操作表如新增.修改.删除.查询.分页查询.统计等业务功能,形成基类,用泛型传参,有利于每个实体对象数据层继承. package com.base.dao; import java.io.Ser ...

  3. 使用SqlSugar封装的数据层基类

    首先简单封装了个DbContext public class DbContext { #region 属性字段 private static string _connectionString; /// ...

  4. C# 基于MySQL的数据层基类(MySQLHelper)

    这里介绍下比较简单的方式,引用MySql.Data.dll然后添加一个MySqlHelper类来对MySql数据库进行访问和操作. 1.将MySql.Data.dll引用到你的项目中 下载地址:MyS ...

  5. BIM工程信息管理系统-EF实体框架数据操作基类

    EF实体框架数据操作基类主要是规范增.改.查.分页.Lambda表达式条件处理,以及异步操作等特性,这样能够尽可能的符合基类这个特殊类的定义,实现功能接口的最大化重用和统一. 1.程序代码 /// & ...

  6. 四、spring集成ibatis进行项目中dao层基类封装

    Apache iBatis(现已迁至Google Code下发展,更名为MyBatis)是当前IT项目中使用很广泛的一个半自动ORM框架,区别于Hibernate之类的全自动框架,iBatis对数据库 ...

  7. mysql批量插入数据的基类

    自己设计的一个mysql数据库批量添加数据的基类.用于批量向mysql数据库添加数据,子类实现起来很简单,自测性能也还不错. 1.基类实现-BatchAddBase using System.Coll ...

  8. 基于SqlSugar的开发框架循序渐进介绍(4)-- 在数据访问基类中对GUID主键进行自动赋值处理

    我们在设计数据库表的时候,往往为了方便,主键ID一般采用字符串类型或者GUID类型,这样对于数据库表记录的迁移非常方便,而且有时候可以在处理关联记录的时候,提前对应的ID值.但有时候进行数据记录插入的 ...

  9. EF实体框架数据操作基类(转)

    //----------------------------------------------------------------// Copyright (C) 2013 河南禄恒软件科技有限公司 ...

随机推荐

  1. python使用(五)

    1.shell_option.py 2.db_option.py 1.shell_option.py # coding=utf8 __author__ = 'SummerChill' import o ...

  2. 源码分析篇 - Android绘制流程(三)requestLayout()与invalidate()流程及Choroegrapher类分析

    本文主要探讨能够触发performTraversals()执行的invalidate().postInvalidate()和requestLayout()方法的流程.在调用这三个方法到最后执行到per ...

  3. StreamSets学习系列之StreamSets是什么?

    不多说,直接上干货! StreamSets是一个侧重数据集成.数据加工流程构建的平台,也是一个开源的产品.通过StreamSets,用户可以方便的接入不同的数据源,并且完成数据加工流程的构建.Stea ...

  4. 全网最详细的Sublime Text 3的安装Package Control插件管理包(图文详解)

    不多说,直接上干货! 全网最详细的Windows里下载与安装Sublime Text *(图文详解) 全网最详细的Sublime Text 3的激活(图文详解) 全网最详细的Sublime Text ...

  5. 只用一招,让你Maven依赖下载速度快如闪电

    一.背景 众所周知,Maven对于依赖的管理让我们程序员感觉爽的不要不要的,但是由于这货是国外出的,所以在我们从中央仓库下载依赖的时候,速度如蜗牛一般,让人不能忍,并且这也是大多数程序员都会遇到的问题 ...

  6. JavaScript创建对象的方法汇总

    JavaScript中的对象 ECMA-262把对象定义为:“无序属性的集合,其属性可以包含基本值.对象或者函数.”严格来讲,这就相当于说对象是一组没有特性顺序的值.对象的每一个属性或方法都有一个名字 ...

  7. TCP保活的必要性

    TCP的长连接理论上只要连接建立后,就会一直保持着.但有时有一些防火墙之类的软件会自动检查主机的网络连接状况,比如说如果发现某个连接在几分钟之内都没有数据通讯,则会关闭这个连接.有时客户端与服务器需要 ...

  8. bigdata-02-hadoop2.8.4-resourceHA安装

    1, 电脑环境准备 1), 关闭selinux vim /etc/selinux/config SELINUX=disabled 2), 时间同步 yum -y install chrony 修改时间 ...

  9. 局域网使用visual studio配合iis调试手机app

    描述:开发一款手机应用程序,服务器配置在iis,当局域网中即只有路由器无外网如何设置实时调试手机应用程序? vs配合iis调试程序的两种方式? 使用vs的debug(f5)调试网站比较常见,然而当网站 ...

  10. FFmpeg进行视频帧提取&音频重采样-Process.waitFor()引发的阻塞超时

    由于产品需要对视频做一系列的解析操作,利用FFmpeg命令来完成视频的音频提取.第一帧提取作为封面图片.音频重采样.字幕压缩等功能: 前一篇文章已经记录了FFmpeg在JAVA中的使用-音频提取&am ...