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 -;
}
catch (Exception ex)
{
//Log.Error(ex + ex.Message);
return -;
}
} /// <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 -;
}
catch (Exception ex)
{
//Log.Error(ex + ex.Message);
return -;
}
}
/// <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 -;
}
catch (Exception ex)
{
//Log.Error(ex + ex.Message);
return -;
}
} #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 -;
}
catch (Exception e)
{
// Log.Error(e + e.Message);
return -;
}
} /// <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 -;
}
catch (Exception e)
{
// Log.Error(e + e.Message);
return -;
}
} /// <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 -;
}
catch (Exception ex)
{
//Log.Error(ex + ex.Message);
return -;
} } /// <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 -;
}
catch (Exception ex)
{
//Log.Error(ex + ex.Message);
return -;
} } /// <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 -;
}
catch (Exception ex)
{
//Log.Error(ex + ex.Message);
return -; } }
#endregion } }

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

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

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

    掌握满足单例模式的必要条件----三私一公. ①私有的构造方法-为了防止在类外使用new关键字实例化对象. ②私有的成员属性-为了防止在类外引入这个存放对象的属性. ③私有的克隆方法-为了防止在类外通 ...

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

    转载自:http://blog.csdn.net/shiqi_614/article/details/8228102 之前做了些线段树相关的题目,开学一段时间后,想着把它整理下,完成了大牛NotOnl ...

  3. #String类简述(小白理解,小白编写,欢迎大神指点,小白跪谢)

    @ 目录 一.前言(可忽略) 二.String变量的认知 三.String类的构造方法 四.String类的基本方法 4.1 toString()方法 4.2 equals()方法 4.3 equal ...

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

    class route{ /** @var null 模块 */ private static $module = null; /** @var null 控制器 */ private static ...

  5. EF 请求数据是缓存 求大神解释

    // //AliexpressEntities MyaliexpressEntities 为了事物一致性 在别的方法里面传过来的 实质还是 (  AliexpressEntities aliexpre ...

  6. 14.翻译系列:从已经存在的数据库中生成上下文类和实体类【EF 6 Code-First系列】

    原文链接:https://www.entityframeworktutorial.net/code-first/code-first-from-existing-database.aspx EF 6 ...

  7. 5.翻译:EF基础系列---EF中的上下文类

    原文地址:http://www.entityframeworktutorial.net/basics/context-class-in-entity-framework.aspx EF中的上下文类是一 ...

  8. 基于Dapper二次封装了一个易用的ORM工具类:SqlDapperUtil

    基于Dapper二次封装了一个易用的ORM工具类:SqlDapperUtil,把日常能用到的各种CRUD都进行了简化封装,让普通程序员只需关注业务即可,因为非常简单,故直接贴源代码,大家若需使用可以直 ...

  9. Timber(对Log类封装的一个工具)

    Timber(对Log类封装的一个工具) https://blog.csdn.net/hzl9966/article/details/51314137 https://www.jianshu.com/ ...

随机推荐

  1. ASP.NET Aries 入门开发教程1:框架下载与运行

    背景: 鉴于框架的使用者越来越多,文档太少,不少用户反映框架的入门门槛太高. 好吧,再辛苦下,抽时间写教程吧! 步骤1:下载框架源码 开源地址:https://github.com/cyq1162/A ...

  2. 【微框架】之一:从零开始,轻松搞定SpringCloud微框架系列--开山篇(spring boot 小demo)

    Spring顶级框架有众多,那么接下的篇幅,我将重点讲解SpringCloud微框架的实现 Spring 顶级项目,包含众多,我们重点学习一下,SpringCloud项目以及SpringBoot项目 ...

  3. 【翻译】Awesome R资源大全中文版来了,全球最火的R工具包一网打尽,超过300+工具,还在等什么?

    0.前言 虽然很早就知道R被微软收购,也很早知道R在统计分析处理方面很强大,开始一直没有行动过...直到 直到12月初在微软技术大会,看到我软的工程师演示R的使用,我就震惊了,然后最近在网上到处了解和 ...

  4. Redis链表实现

    链表在 Redis 中的应用非常广泛, 比如列表键的底层实现之一就是链表: 当一个列表键包含了数量比较多的元素, 又或者列表中包含的元素都是比较长的字符串时, Redis 就会使用链表作为列表键的底层 ...

  5. Web安全相关(四):过多发布(Over Posting)

    简介 过多发布的内容相对比较简单,因此,我只打算把原文中的一些关键信息翻译一下.原文链接如下: http://www.asp.net/mvc/overview/getting-started/gett ...

  6. Python爬虫小白入门(四)PhatomJS+Selenium第一篇

    一.前言 在上一篇博文中,我们的爬虫面临着一个问题,在爬取Unsplash网站的时候,由于网站是下拉刷新,并没有分页.所以不能够通过页码获取页面的url来分别发送网络请求.我也尝试了其他方式,比如下拉 ...

  7. GSD_WeiXin(高仿微信)应用源码

    高仿微信计划:已经实现功能 1.微信首页(cell侧滑编辑.下拉眼睛动画.下拉拍短视频.点击进入聊天详情界面) 2.通讯录(联系人字母排序.搜索界面) 3.发现(朋友圈) 4.我(界面) 待实现功能( ...

  8. 如何手动安装MySql

    想安装当然要先有一个MySql的安装包 这里使用的是mysql-5.7.12-winx64 安装包百度云:http://pan.baidu.com/s/1kVAuXuv  密码:hr39 1.要将压缩 ...

  9. 智能头盔 "Livall携全球首款智能骑行头盔亮相CES"

    LIVALL是全球首创集音乐.通讯.智能灯光为一体的智能骑行头盔的研发者,日前Livall携旗下智能骑行头盔BH 100和BH 60参展CES 2017,这也是目前世全球首款智能骑行头盔类产品,同时亮 ...

  10. MySql 死锁时的一种解决办法

    转自:http://blog.csdn.net/mchdba/article/details/38313881 之前也遇到一次,今天又遇到了这个问题,所以这次必须解决,网上找到这篇文章帮了大忙,方便以 ...