自己封装了一个EF的上下文类.,分享一下,顺便求大神指点

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Core.Objects;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Migrations;
using System.Data.Entity.Validation;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using EntityFramework.Extensions;
using System.Threading.Tasks;
//using log4net;
//using log4net.Core;

namespace _6._0Test
{
    /// <summary>
    /// 上下文静态实体类
    /// </summary>
    public static class DbContentEntity
    {
        /// <summary>
        /// 静态初始化
        /// </summary>
        static DbContentEntity()
        {
            if (string.IsNullOrEmpty(ConnectionString))
                return;
            if (_entities == null)
            {
                _entities = new TestEntities(ConnectionString);
                _entities.Configuration.ValidateOnSaveEnabled = false;
            }
            if (_entities.Database.Connection.State == ConnectionState.Closed && _entities.Database.Connection.State != ConnectionState.Connecting)
            {
                _entities.Database.Connection.Open();
            }
        }

        /// <summary>
        /// 静态连接字符串
        /// </summary>

        public static string ConnectionString
        {
            get { return  ConfigurationManager.ConnectionStrings["TestEntities"].ConnectionString; }
        }

        /// <summary>
        /// 静态实体
        /// </summary>
        private static TestEntities _entities;
        /// <summary>
        /// 对外实体
        /// </summary>
        public static TestEntities Entities
        {
            get
            {
                if (string.IsNullOrEmpty(ConnectionString))
                    return null;
                return _entities ?? (_entities = new TestEntities(ConnectionString));
            }
        }

    }

    /// <summary>
    /// 上下文类
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public abstract class ModelContext<T>  where T : class
    {
        //日志,可自行拓展
        //public static ILog Log = LogManager.GetLogger(typeof(T).Name);

        /// <summary>
        /// 返回上下文实体
        /// </summary>
        protected TestEntities Entities
        {
            get { return DbContentEntity.Entities; }
        }

        private DbSet<T> _model;

        protected  DbSet<T> Model
        {
            get { return _model ?? (_model = Entities.Set<T>()); }
        }

        #region                =====查询用方法=====

        /// <summary>
        /// 根据条件查询实体
        /// </summary>
        /// <param name="where">条件</param>
        /// <returns>实体</returns>
        public virtual T Get(Expression<Func<T, bool>> @where)
        {

            return Model.FirstOrDefault(where);

        }

        /// <summary>
        /// 根据条件查询实体(异步)
        /// </summary>
        /// <param name="where">条件</param>
        /// <returns>实体</returns>
        public async virtual  Task<T> GetAsync(Expression<Func<T, bool>> @where)
        {

            return await Model.FirstOrDefaultAsync(where);

        }

        /// <summary>
        /// 根据条件查询实体集合(需自行tolist,自行异步)
        /// </summary>
        /// <param name="where">查询条件</param>
        /// <returns></returns>
        public virtual IQueryable<T> GetList(Expression<Func<T, bool>> @where)
        {

            return Model.AsNoTracking().Where(where);

        }

        /// <summary>
        /// 根据条件查询实体集合(需自行tolist,自行异步)
        /// </summary>
        /// <param name="where">查询条件</param>
        /// <returns></returns>
        public async virtual Task<IQueryable<T>> GetListAsync(Expression<Func<T, bool>> @where)
        {

            return await Task.Run(()=>Model.AsNoTracking().Where(where));

        }

        /// <summary>
        /// 根据传进来的实体类型查询该实体的集合
        /// </summary>
        /// <typeparam name="TM">实体类型</typeparam>
        /// <param name="where">查询条件</param>
        /// <returns></returns>
        public virtual IQueryable<TM> GetList<TM>(Expression<Func<TM, bool>> @where) where TM : class
        {

            var model = Entities.Set<TM>();
            return  model.AsNoTracking().Where(where);

        }
        /// <summary>
        /// 根据传进来的实体类型查询该实体(异步)
        /// </summary>
        /// <typeparam name="TM">实体类型</typeparam>
        /// <param name="where">查询条件</param>
        /// <returns></returns>
        public async virtual Task<TM> GetAsync<TM>(Expression<Func<TM, bool>> @where) where TM : class
        {

            var model = Entities.Set<TM>();
            return await model.FirstOrDefaultAsync(where);

        }

        /// <summary>
        /// 根据条件查询实体数量
        /// </summary>
        /// <typeparam name="TM">实体类型</typeparam>
        /// <param name="where">查询条件</param>
        /// <returns></returns>
        public virtual int Cout<TM>(Expression<Func<TM, bool>> @where) where TM : class
        {
            try
            {
                var model = Entities.Set<TM>();
                return model.AsNoTracking().Count(where);
            }
            catch (DbEntityValidationException dbEx)
            {
                //Log.Error(dbEx + dbEx.Message);
                return -1;
            }
            catch (Exception ex)
            {
                //Log.Error(ex + ex.Message);
                return -1;
            }
        }

        /// <summary>
        /// 根据条件查询实体数量(异步)
        /// </summary>
        /// <typeparam name="TM">实体类型</typeparam>
        /// <param name="where">查询条件</param>
        /// <returns></returns>
        public async virtual Task<int>  CoutAsync<TM>(Expression<Func<TM, bool>> @where) where TM : class
        {
            try
            {
                var model = Entities.Set<TM>();
                return await model.AsNoTracking().CountAsync(where);
            }
            catch (DbEntityValidationException dbEx)
            {
                //Log.Error(dbEx + dbEx.Message);
                return -1;
            }
            catch (Exception ex)
            {
                //Log.Error(ex + ex.Message);
                return -1;
            }
        }
        /// <summary>
        /// 根据条件查询实体数量
        /// </summary>
        /// <param name="where"></param>
        /// <returns></returns>
        public async virtual Task<int> Count(Expression<Func<T, bool>> @where)
        {
            try
            {
                var model = Entities.Set<T>();
                return await model.AsNoTracking().CountAsync(where);
            }
            catch (DbEntityValidationException dbEx)
            {
                //Log.Error(dbEx + dbEx.Message);
                return -1;
            }
            catch (Exception ex)
            {
                //Log.Error(ex + ex.Message);
                return -1;
            }
        }

#endregion

        #region ====添加用方法====
        /// <summary>
        /// 添加实体
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        public virtual bool Add(T m)
        {
            try
            {

                Model.Add(m);
                Entities.SaveChanges();
            }
            catch (DbEntityValidationException dbEx)
            {
                //Log.Error(dbEx + dbEx.Message);
                return false;
            }
            catch (Exception ex)
            {
                //Log.Error(ex + ex.Message);
                return false;
            }
            return true;
        }
        /// <summary>
        /// 添加实体(异步)
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        public async virtual Task<bool> AddAsync(T m)
        {
            try
            {

                Model.Add(m);
                await  Entities.SaveChangesAsync();
            }
            catch (DbEntityValidationException dbEx)
            {
                //Log.Error(dbEx + dbEx.Message);
                return false;
            }
            catch (Exception ex)
            {
                //Log.Error(ex + ex.Message);
                return false;
            }
            return true;
        }

        /// <summary>
        /// 根据类型添加实体
        /// </summary>
        /// <typeparam name="TM"></typeparam>
        /// <param name="tm"></param>
        /// <returns></returns>
        public virtual bool Add<TM>(TM tm) where TM : class
        {
            try
            {
                var model = Entities.Set<TM>();
                model.Add(tm);
                Entities.SaveChanges();
            }
            catch (DbEntityValidationException dbex)
            {
                //Log.Error(dbex + dbex.Message);
                return false;
            }
            catch (Exception ex)
            {
                //Log.Error(ex + ex.Message);
                return false;
            }
            return true;
        }

        /// <summary>
        /// 批量添加实体
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        public virtual bool AddRange(IEnumerable<T> m)
        {

            try
            {
                Model.AddRange(m);
                Entities.SaveChanges();
            }
            catch (DbEntityValidationException dbEx)
            {
                //Log.Error(dbEx + dbEx.Message);
                return false;
            }
            catch (Exception ex)
            {
                //Log.Error(ex + ex.Message);
                return false;
            }
            return true;
        }
        /// <summary>
        /// 批量添加实体(异步)
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        public async virtual Task<bool> AddRangeAsync(IEnumerable<T> m)
        {

            try
            {
                Model.AddRange(m);
                await Entities.SaveChangesAsync();
            }
            catch (DbEntityValidationException dbEx)
            {
                //Log.Error(dbEx + dbEx.Message);
                return false;
            }
            catch (Exception ex)
            {
                //Log.Error(ex + ex.Message);
                return false;
            }
            return true;
        }

        #endregion

        #region ====修改用方法====
        /// <summary>
        /// 修改实体
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public virtual bool Update(T t)
        {

            try
            {

                Model.Attach(t);
                Entities.Entry(t).State = EntityState.Modified;
                Entities.SaveChanges();
            }
            catch (DbEntityValidationException dbEx)
            {
                //Log.Error(dbEx + dbEx.Message);
                return false;
            }
            catch (Exception ex)
            {
                //Log.Error(ex + ex.Message);
                return false;
            }
            return true;
        }

        /// <summary>
        /// 修改实体(异步)
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public async virtual Task<bool> UpdateAsync(T t)
        {

            try
            {

                Model.Attach(t);
                Entities.Entry(t).State = EntityState.Modified;
                await Entities.SaveChangesAsync();
            }
            catch (DbEntityValidationException dbEx)
            {
                //Log.Error(dbEx + dbEx.Message);
                return false;
            }
            catch (Exception ex)
            {
                //Log.Error(ex + ex.Message);
                return false;
            }
            return true;
        }
        /// <summary>
        /// 根据类型修改实体
        /// </summary>
        /// <typeparam name="TM"></typeparam>
        /// <param name="tm"></param>
        /// <returns></returns>
        public virtual bool Update<TM>(TM tm) where TM : class
        {
            try
            {
                var model = Entities.Set<TM>();
                model.Attach(tm);
                Entities.Entry(tm).State = EntityState.Modified;
                Entities.SaveChanges();
            }
            catch (DbEntityValidationException dbEx)
            {
                //Log.Error(dbEx + dbEx.Message);
                return false;
            }
            catch (Exception ex)
            {
                //Log.Error(ex + ex.Message);
                return false;
            }
            return true;
        }

        /// <summary>
        /// 批量更新数据
        /// </summary>
        /// <param name="where">更新数据的条件 如:u => u.FirstName == "firstname"</param>
        /// <param name="ex">更新的值 如:u=>new User{FirstName = "newfirstname"}</param>
        /// <returns>返回影响的条数</returns>
        public virtual int Update(Expression<Func<T, bool>> @where, Expression<Func<T, T>> ex)
        {
            try
            {
                return Model.Where(where).Update(ex);
            }
            catch (DbEntityValidationException dbEx)
            {
                //Log.Error(dbEx + dbEx.Message);
                return -1;
            }
            catch (Exception e)
            {
               // Log.Error(e + e.Message);
                return -1;
            }
        }

        /// <summary>
        /// 批量更新数据(异步)
        /// </summary>
        /// <param name="where">更新数据的条件 如:u => u.FirstName == "firstname"</param>
        /// <param name="ex">更新的值 如:u=>new User{FirstName = "newfirstname"}</param>
        /// <returns>返回影响的条数</returns>
        public async virtual  Task<int> UpdateAsync(Expression<Func<T, bool>> @where, Expression<Func<T, T>> ex)
        {
            try
            {
                return  await  Model.Where(where).UpdateAsync(ex);
            }
            catch (DbEntityValidationException dbEx)
            {
                //Log.Error(dbEx + dbEx.Message);
                return -1;
            }
            catch (Exception e)
            {
                // Log.Error(e + e.Message);
                return -1;
            }
        }

       /// <summary>
       /// 添加或者修改实体(无则添加,有则修改)
       /// </summary>
       /// <param name="m"></param>
       /// <returns></returns>
        public virtual bool AddOrUpdate(T[] m)
        {
            try
            {
                Model.AddOrUpdate(m);
                Entities.SaveChanges();
            }
            catch (DbEntityValidationException dbEx)
            {
               // Log.Error(dbEx + dbEx.Message);
                return false;
            }
            catch (Exception ex)
            {
                //Log.Error(ex + ex.Message);
                return false;
            }
            return true;
        }

        /// <summary>
        /// 添加或者修改实体(无则添加,有则修改,异步)
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        public async virtual Task<bool> AddOrUpdateAsync(T[] m)
        {
            try
            {
                Model.AddOrUpdate(m);
                await Entities.SaveChangesAsync();
            }
            catch (DbEntityValidationException dbEx)
            {
                // Log.Error(dbEx + dbEx.Message);
                return false;
            }
            catch (Exception ex)
            {
                //Log.Error(ex + ex.Message);
                return false;
            }
            return true;
        }

        #endregion

        #region ===事务====
        /// <summary>
        /// 运行基本事务,返回bool值
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>

        protected bool RunTransaction(Action<DbSet<T>> model)
        {

            using (var transaction = Entities.Database.BeginTransaction())
            {
                try
                {
                    model.Invoke(Model);
                    Entities.SaveChanges();
                    transaction.Commit();
                    return true;
                }
                catch (DbEntityValidationException dbEx)
                {
                    //Log.Error("EXEC RunTransaction Error:" + dbEx + dbEx.Message);
                    return false;
                }
                catch (Exception ex)
                {
                    //Log.Error("EXEC RunTransaction Error:" + ex + ex.Message);
                    transaction.Rollback();
                    return false;

                }
            }

        }
        /// <summary>
        /// 运行基本事务,返回bool值(异步)
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>

        protected async Task<bool> RunTransactionAsync(Action<DbSet<T>> model)
        {

            using (var transaction = Entities.Database.BeginTransaction())
            {
                try
                {
                    model.Invoke(Model);
                    await Entities.SaveChangesAsync();
                    transaction.Commit();
                    return true;
                }
                catch (DbEntityValidationException dbEx)
                {
                    //Log.Error("EXEC RunTransaction Error:" + dbEx + dbEx.Message);
                    return false;
                }
                catch (Exception ex)
                {
                    //Log.Error("EXEC RunTransaction Error:" + ex + ex.Message);
                    transaction.Rollback();
                    return false;

                }
            }

        }
        #endregion

        #region======删除用方法====
        /// <summary>
        /// 删除实体
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public virtual bool Remove(T t)
        {
            try
            {
                Model.Remove(t);
                Entities.SaveChanges();

            }
            catch (DbEntityValidationException dbEx)
            {
                //Log.Error(dbEx + dbEx.Message);
                return false;
            }
            catch (Exception ex)
            {
                //Log.Error(ex + ex.Message);
                return false;
            }
            return true;

        }

        /// <summary>
        /// 删除实体(异步)
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public async virtual Task<bool> RemoveAsync(T t)
        {
            try
            {
                Model.Remove(t);
                await Entities.SaveChangesAsync();

            }
            catch (DbEntityValidationException dbEx)
            {
                //Log.Error(dbEx + dbEx.Message);
                return false;
            }
            catch (Exception ex)
            {
                //Log.Error(ex + ex.Message);
                return false;
            }
            return true;

        }

        /// <summary>
        /// 根据类型删除实体
        /// </summary>
        /// <typeparam name="TM"></typeparam>
        /// <param name="m"></param>
        /// <returns></returns>
        public virtual bool Remove<TM>(TM m) where TM : class
        {
            try
            {
                var model = Entities.Set<TM>();
                model.Remove(m);
                Entities.SaveChanges();

            }
            catch (DbEntityValidationException dbEx)
            {
                //Log.Error(dbEx + dbEx.Message);
                return false;
            }
            catch (Exception ex)
            {
                //Log.Error(ex + ex.Message);
                return false;
            }
            return true;
        }

        /// <summary>
        ///批量删除实体
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        public virtual int RemoveRange(IEnumerable<T> m)
        {

            try
            {
                Model.RemoveRange(m);
                return Entities.SaveChanges();
            }
            catch (DbEntityValidationException dbEx)
            {
                //Log.Error(dbEx + dbEx.Message);
                return -1;
            }
            catch (Exception ex)
            {
                //Log.Error(ex + ex.Message);
                return -1;
            }

        }

        /// <summary>
        ///批量删除实体(异步)
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        public async virtual  Task<int> RemoveRangeAsync(IEnumerable<T> m)
        {

            try
            {
                Model.RemoveRange(m);
                return await Entities.SaveChangesAsync();
            }
            catch (DbEntityValidationException dbEx)
            {
                //Log.Error(dbEx + dbEx.Message);
                return -1;
            }
            catch (Exception ex)
            {
                //Log.Error(ex + ex.Message);
                return -1;
            }

        }

        /// <summary>
        /// 根据类型批量删除实体
        /// </summary>
        /// <typeparam name="TM"></typeparam>
        /// <param name="tmMs"></param>
        /// <returns></returns>
        public virtual int RemoveRange<TM>(IEnumerable<TM> tmMs) where TM : class
        {
            try
            {
                var model = Entities.Set<TM>();
                model.RemoveRange(tmMs);
                return Entities.SaveChanges();
            }
            catch (DbEntityValidationException dbEx)
            {
                //Log.Error(dbEx + dbEx.Message);
                return -1;
            }
            catch (Exception ex)
            {
                //Log.Error(ex + ex.Message);
                return -1;

            }

        }
        #endregion

    }

}

..求大神指点一下..哪里有问题..我在改改..

时间: 2024-11-05 20:32:39

自己封装了一个EF的上下文类.,分享一下,顺便求大神指点的相关文章

PHP封装的一个单例模式Mysql操作类

掌握满足单例模式的必要条件----三私一公. ①私有的构造方法-为了防止在类外使用new关键字实例化对象. ②私有的成员属性-为了防止在类外引入这个存放对象的属性. ③私有的克隆方法-为了防止在类外通过clone成生另一个对象. ④公有的静态方法-为了让用户进行实例化对象的操作. DB类及相关表操作: class mysql_db{     //1.私有的静态属性   private static $dbcon = false;     //2.私有的构造方法   private functio

自己封装的一个mysql数据库工具类

<?php class SqlHelper{ public $conn; //连接资源变量 public $host; //主机 public $user;  //用户名 public $password; //密码 public $db; //数据库 function __construct($host="localhost",$user="root",$password,$db){ $this->host=$host; $this->user=

线段树总结 (转载 里面有扫描线类 还有NotOnlySuccess线段树大神的地址)

转载自:http://blog.csdn.net/shiqi_614/article/details/8228102 之前做了些线段树相关的题目,开学一段时间后,想着把它整理下,完成了大牛NotOnlySuccess的博文“完全版线段树”里的大部分题目,其博文地址Here,然后也加入了自己做过的一些题目.整理时,更新了之前的代码风格,不过旧的代码仍然保留着. 同样分成四类,不好归到前四类的都分到了其他.树状数组能做,线段树都能做(如果是内存限制例外),所以也有些树状数组的题目,会标示出来,并且放

php 自制简单路由类 望大神指点

class route{ /** @var null 模块 */ private static $module = null; /** @var null 控制器 */ private static $controller = null; /** @var null 方法 */ private static $action = null; /** @var 控制器url */ private static $controllerPath; /** * route constructor. * @

VS 中的一个BUG?求大神帮我解答下。

首先,希望知道这个问题的人能够帮我解答下. 来看代码: int main() { long long int result=-321; cout<<result<<endl; if(INT_MIN==-2147483648) cout<<"相等"<<endl; if( result<-2147483648) cout<<"1"<<endl; if( result<INT_MIN) c

被困扰了一个下午,求大神解答。VC6.0能编译通过,VS2013报错错误。

是一个与链表相关的代码,输入学生总人数及,每个学生的姓名成绩,并将输入的内容显示出来..VC6.0能编译通过,VS2013报错error C4703: 使用了可能未初始化的本地指针变量“p1”代码如下:#define _CRT_SECURE_NO_WARNINGS#include<stdio.h>#include<stdlib.h>typedef struct student{char name[15];int mark;struct student *next;}Node,*no

刚学前端,最近遇到一个jQuery的问题,还请路过的大神帮忙解决下

我打算做一个自动轮播图,效果如图所示,小圆点点击效果已经OK,我想让图片上那个左右按钮与小圆点对应实现一个图片点击轮播(首尾相连). 之后再添加一个时间轮播效果(首尾相连). 以下是css代码 <style type="text/css"> * { margin: 0; padding: 0; text-decoration: none; list-style-type: none; } /*切换按钮*/ .arrow{ width: 50px; height: 50px;

开发的一个android程序,总是显示无法运行,就退出了。但是没有报错。求大神解救啊!

============问题描述============ 代码如下: 在网上查有人说是intent的问题 原来没有加入监听器的时候没有问题 我是个新手,问题有点没水平啦~ 求大神啊.谢谢谢谢 ============解决方案1============ 把log贴上来看看,是不是menu这个activity没有在manifest 声明 ============解决方案2============ setonclicklistener那句话,把new helplistener前面的那个类型转换删除 =

关于成员变量和局部变量的一个小问题,求大神指导下。

public class Test{ public static void main(String[] args){ int time=0; for(int i=2;i<100;i++){ //int time=0; for(int j=1;j<i;j++){ if(i%j==0){ time+=1; } } if(time==1){ System.out.print(i+"\t"); } } } 上面的代码是求100以内的素数,我发现"int time=0;&q