代码改变世界

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

2014-06-13 14:02  gdutzhulm  阅读(447)  评论(0编辑  收藏  举报

//----------------------------------------------------------------
// Copyright (C) 2013 河南禄恒软件科技有限公司
//
// 功能描述:实体框架数据仓储的操作接口,包含增删改查接口
//
//----------------------------------------------------------------
using System;
using System.Data.Entity.Infrastructure;
using System.Data.Objects;
using System.Linq;
using System.Linq.Expressions;
using System.Data.Entity;
using EntityFramework.Extensions;

namespace Qmvc.DataAccess.EntityRepository
{
    /// <summary>
    ///     实体框架数据仓储的基类
    /// </summary>
    /// <typeparam name="TContext">提供用于查询和使用对象形式的实体数据的功能的实体上下文</typeparam>
    /// <typeparam name="T">表示用于执行创建、读取、更新和删除操作的类型化实体集</typeparam>
    public abstract class EntityRepositoryBase<TContext, T> : IRepository<T>
        where TContext : DbContext
        where T : class, new()
    {
        /// <summary>
        ///     表示用于执行创建、读取、更新和删除操作的类型化实体集
        /// </summary>
        private DbSet<T> _dbSet;

        /// <summary>
        ///
        /// </summary>
        protected EntityRepositoryBase()
        {
            IsOwnContext = false;
        }

        /// <summary>
        ///     提供用于查询和使用对象形式的实体数据的功能的实体上下文
        /// </summary>
        protected virtual TContext Context { get; set; }

        /// <summary>
        ///     表示用于执行创建、读取、更新和删除操作的类型化实体集
        /// </summary>
        protected virtual DbSet<T> Set
        {
            get { return _dbSet ?? (_dbSet = Context.Set<T>()); }
            set { _dbSet = value; }
        }

        /// <summary>
        ///     是否拥有上下文
        /// </summary>
        protected bool IsOwnContext { get; set; }

        /// <summary>
        ///     返回一个 System.Linq.IQueryable
        /// </summary>
        /// <returns>一个 System.Linq.IQueryable,包含满足由 predicate 指定的条件的元素</returns>
        public virtual IQueryable<T> All()
        {
            return Set.Where(p => true);
        }

        /// <summary>
        ///     返回一个 System.Linq.IQueryable,包含满足由 predicate 指定的条件的元素
        /// </summary>
        /// <param name="predicate">用于测试每个元素是否满足条件的函数</param>
        /// <returns>一个 System.Linq.IQueryable,包含满足由 predicate 指定的条件的元素</returns>
        public virtual IQueryable<T> Where(Expression<Func<T, bool>> predicate)
        {
            var query = Set.Where(predicate);
            return query;
        }

        /// <summary>
        ///     返回一个 System.Linq.IQueryable<T>,包含满足由 predicate 和 分页参数 指定的条件的元素,并根据键对其元素排序</T>
        /// </summary>
        /// <param name="predicate">用于测试每个元素是否满足条件的函数</param>
        /// <param name="pageSize">页大小</param>
        /// <param name="pageIndex">页码</param>
        /// <param name="orderingSelector">用于从元素中提取键的函数</param>
        /// <param name="orderBy">排序类型</param>
        /// <param name="recCount">总数量</param>
        /// <returns>一个 System.Linq.IQueryable<T/>,包含满足由 predicate 和 分页参数 指定的条件的元素,并根据键对其元素排序</returns>
        public virtual IQueryable<T> Where<TKey>(Expression<Func<T, bool>> predicate, int pageSize, int pageIndex,
            Expression<Func<T, TKey>> orderingSelector, OrderingOrders orderBy, out int recCount)
        {
            IQueryable<T> query = Set.Where(predicate);
            recCount = query.Count();
            query = orderBy == OrderingOrders.ASC
                ? query.OrderBy(orderingSelector).AsQueryable()
                : query.OrderByDescending(orderingSelector).AsQueryable();

            query = query.Skip((pageIndex - 1) * pageSize).Take(pageSize);

            return query;
        }

        /// <summary>
        ///     返回一个 System.Linq.IQueryable<T/>,包含满足由 predicate 指定的条件的元素,并根据键对其元素排序
        /// </summary>
        /// <param name="predicate">用于测试每个元素是否满足条件的函数</param>
        /// <param name="orderingSelector">用于从元素中提取键的函数</param>
        /// <param name="orderBy">排序</param>
        /// <returns>一个 System.Linq.IQueryable<T/>,包含满足由 predicate 指定的条件的元素,并根据键对其元素排序</returns>
        public virtual IQueryable<T> Where<TKey>(Expression<Func<T, bool>> predicate,
            Expression<Func<T, TKey>> orderingSelector, OrderingOrders orderBy)
        {
            IQueryable<T> query = Set.Where(predicate);
            query = orderBy == OrderingOrders.ASC
                ? query.OrderBy(orderingSelector).AsQueryable()
                : query.OrderByDescending(orderingSelector).AsQueryable();
            return query;
        }


        /// <summary>
        /// 通过SQL查询数据结果
        /// </summary>
        /// <typeparam name="TKey"></typeparam>
        /// <param name="sql"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public virtual IQueryable<T> Where<TKey>(string sql, params object[] parameters)
        {
            IQueryable<T> query = Set.SqlQuery(sql, parameters).AsQueryable();
            return query;
        }


        /// <summary>
        ///     返回序列的唯一元素;如果该序列并非恰好包含一个元素,则会引发异常。
        /// </summary>
        /// <param name="predicate">用于测试每个元素是否满足条件的函数</param>
        /// <returns>单个元素</returns>
        public virtual T Single(Expression<Func<T, bool>> predicate)
        {
            return Set.Single(predicate);
        }

        /// <summary>
        ///     返回序列的唯一元素;如果该序列并非恰好包含一个元素,则会引发异常。
        /// </summary>
        /// <param name="predicate">用于测试每个元素是否满足条件的函数</param>
        /// <param name="orderingSelector">用于从元素中提取键的函数</param>
        /// <param name="orderBy">排序</param>
        /// <returns>单个元素</returns>
        public virtual T Single<TKey>(Expression<Func<T, bool>> predicate, Expression<Func<T, TKey>> orderingSelector,
            OrderingOrders orderBy)
        {
            IQueryable<T> query = Set.Where(predicate);
            query = orderBy == OrderingOrders.ASC
                ? query.OrderBy(orderingSelector).AsQueryable()
                : query.OrderByDescending(orderingSelector).AsQueryable();
            return query.Single();
        }

        /// <summary>
        ///     返回序列中满足指定条件的唯一元素;如果序列中不包含任何元素,则返回默认值
        /// </summary>
        /// <param name="predicate">用于测试每个元素是否满足条件的函数</param>
        /// <returns>唯一元素</returns>
        public virtual T FirstOrDefault(Expression<Func<T, bool>> predicate)
        {
            return Set.FirstOrDefault(predicate);
        }

        /// <summary>
        ///     返回序列中满足指定条件的唯一元素;如果序列中不包含任何元素,则返回默认值
        /// </summary>
        /// <param name="predicate">用于测试每个元素是否满足条件的函数</param>
        /// <param name="orderingSelector">用于从元素中提取键的函数</param>
        /// <param name="orderBy">排序</param>
        /// <returns>唯一元素</returns>
        public virtual T FirstOrDefault<TKey>(Expression<Func<T, bool>> predicate,
            Expression<Func<T, TKey>> orderingSelector, OrderingOrders orderBy)
        {
            IQueryable<T> query = Set.Where(predicate);
            query = orderBy == OrderingOrders.ASC
                ? query.OrderBy(orderingSelector).AsQueryable()
                : query.OrderByDescending(orderingSelector).AsQueryable();
            return query.FirstOrDefault();
        }

        /// <summary>
        ///     返回指定序列中满足条件的元素数量
        /// </summary>
        /// <param name="predicate">用于测试每个元素是否满足条件的函数</param>
        /// <returns>元素数量</returns>
        public virtual int Count(Expression<Func<T, bool>> predicate)
        {
            return Set.Count(predicate);
        }

        /// <summary>
        ///     将对象添加到当前实体集中的对象上下文;如果 IsOwnContex == true,将对象保存到数据源
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns>操作是否成功</returns>
        public virtual bool Add(T entity)
        {
            bool isSucceed;

            Set.Add(entity);

            if (IsOwnContext)
                isSucceed = Context.SaveChanges() > 0;
            else
                isSucceed = true;

            return isSucceed;
        }

        /// <summary>
        ///     将对象标记为待删除;如果 IsOwnContex == true,将对象保存到数据源
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns>操作是否成功</returns>
        public virtual bool Delete(T entity)
        {
            bool isSucceed;

            Set.Remove(entity);

            if (IsOwnContext)
                isSucceed = Context.SaveChanges() > 0;
            else
                isSucceed = true;

            return isSucceed;
        }

        /// <summary>
        ///     将满足 predicate 指定的条件的元素对象标记为待删除;
        /// </summary>
        /// <param name="predicate">用于测试每个元素是否满足条件的函数</param>
        /// <returns>操作是否成功</returns>
        public virtual bool Delete(Expression<Func<T, bool>> predicate)
        {
            return Set.Where(predicate).Delete() > 0;
        }

        /// <summary>
        ///     将满足 predicate 指定的条件的元素对象更新为满足 updatePredicate 条件的属性;
        /// </summary>
        /// <param name="predicate">用于测试每个元素是否满足条件的函数</param>
        /// <param name="updatePredicate">用于构建对象的函数</param>
        /// <returns>操作是否成功</returns>
        public virtual bool Update(Expression<Func<T, bool>> predicate, Expression<Func<T, T>> updatePredicate)
        {
            return Set.Update(predicate, updatePredicate) > 0;
        }


        /// <summary>
        ///
        /// </summary>
        public void Dispose()
        {
            if ((IsOwnContext) && (Context != null))
            {
                Context.Dispose();
            }
            GC.SuppressFinalize(this);
        }

        /// <summary>
        ///     临时把实休对象保存在管理对象中
        /// </summary>
        /// <param name="entity"></param>
        public virtual void AddEntity(T entity)
        {
            Set.Add(entity);
        }
       
        /// <summary>
        ///     将所有更新保存到数据源并重置对象上下文中的更改跟踪。
        /// </summary>
        /// <returns>
        ///     在调用 System.Data.Objects.ObjectContext.SaveChanges() 时处于
        ///     System.Data.EntityState.Added、System.Data.EntityState.Modified或 System.Data.EntityState.Deleted 状态的对象数。
        /// </returns>
        public int SaveChanges()
        {
            return Context.SaveChanges();
        }
    }
}

 

转自:http://www.cnblogs.com/henanluheng/p/3785596.html