这段时间研究了orm框架EF 写一写研究的历程和心得

先贴上核心代码

 public interface ITransaction
{
bool IsTransaction { get;} void BeginTransaction(); int Commit(); void Rollback();
}
 public class BaseRepository : ITransaction, IDisposable
{ private XFDbContext dbContext; /// <summary>
/// 连接字符串名称
/// </summary>
public string ConnectionName { get; set; } private bool disposed; public BaseRepository()
{
this.dbContext = new XFDbContext();
this.IsTransaction = false;
} public BaseRepository(string connectionName)
{
this.ConnectionName = connectionName;
this.dbContext = new XFDbContext(ConnectionName);
this.IsTransaction = false;
} #region 增删改 /// <summary>
/// 新增实体对象
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <param name="model"></param>
/// <returns></returns>
public int Insert<TEntity>(TEntity model) where TEntity : class
{
return this.ChangeObjectState<TEntity>(model, EntityState.Added);
} /// <summary>
/// 新增实体对象集合
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <param name="models"></param>
/// <returns></returns>
public int Insert<TEntity>(IEnumerable<TEntity> models) where TEntity : class
{
return this.ChangeObjectState<TEntity>(models, EntityState.Added);
} /// <summary>
/// 持久化对象更改
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <param name="model"></param>
/// <returns></returns>
public int Update<TEntity>(TEntity model) where TEntity : class
{
return this.ChangeObjectState<TEntity>(model, EntityState.Modified);
} /// <summary>
/// 更新对象集合
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <param name="models"></param>
/// <returns></returns>
public int Update<TEntity>(IEnumerable<TEntity> models) where TEntity : class
{
return this.ChangeObjectState<TEntity>(models, EntityState.Modified);
} /// <summary>
/// 更新对象部分属性
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <param name="predicate"></param>
/// <param name="updateAction"></param>
/// <returns></returns>
public int Update<TEntity>(Expression<Func<TEntity, bool>> predicate, Action<TEntity> updateAction) where TEntity : class
{
if (predicate == null)
throw new ArgumentNullException("predicate");
if (updateAction == null)
throw new ArgumentNullException("updateAction"); //dbContext.Configuration.AutoDetectChangesEnabled = true;
var _model = dbContext.Set<TEntity>().Where(predicate).ToList();
if (_model == null) return ;
_model.ForEach(p =>
{
updateAction(p);
dbContext.Entry<TEntity>(p).State = EntityState.Modified;
});
return Save();
} /// <summary>
/// 删除实体对象
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <param name="model"></param>
/// <returns></returns>
public int Delete<TEntity>(TEntity model) where TEntity : class
{
return this.ChangeObjectState<TEntity>(model, EntityState.Deleted);
} /// <summary>
/// 删除实体对象集合
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <param name="models"></param>
/// <returns></returns>
public int Delete<TEntity>(IEnumerable<TEntity> models) where TEntity : class
{
return this.ChangeObjectState<TEntity>(models, EntityState.Deleted);
} /// <summary>
/// 删除实体对象集合(符合部分条件的)
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <param name="predicate"></param>
/// <returns></returns>
public int Delete<TEntity>(Expression<Func<TEntity, bool>> predicate) where TEntity : class
{
List<TEntity> _list = null; _list = dbContext.Set<TEntity>().Where(predicate).ToList();
foreach (var item in _list)
{
dbContext.Entry<TEntity>(item).State = EntityState.Deleted;
}
return Save();
} #endregion 增删改 #region 查询
public IList<TEntity> Search<TEntity>(Expression<Func<TEntity, bool>> predicate = null) where TEntity : class
{
if (predicate == null)
{
return dbContext.Set<TEntity>().ToList();
}
else
{
return dbContext.Set<TEntity>().Where(predicate).ToList();
} } /// <summary>
/// 查询单个记录
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <param name="predicate"></param>
/// <returns></returns>
public TEntity SearchFirstOrDefault<TEntity>(Expression<Func<TEntity, bool>> predicate = null) where TEntity : class
{
if (predicate == null)
{
return dbContext.Set<TEntity>().FirstOrDefault();
}
else
{
return dbContext.Set<TEntity>().Where(predicate).FirstOrDefault();
} } /// <summary>
/// 查询多笔记录
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <param name="predicate"></param>
/// <returns></returns>
public IList<TEntity> SearchList<TEntity>(Expression<Func<TEntity, bool>> predicate = null) where TEntity : class
{ if (predicate == null)
{
return dbContext.Set<TEntity>().ToList();
}
else
{
return dbContext.Set<TEntity>().Where(predicate).ToList();
}
} public IList<TEntity> GetPaged<TEntity>(out int total, Expression<Func<TEntity, bool>> filter = null, Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null, int index = , int size = ) where TEntity : class
{
int skipCount = (index - ) * size;
var query = Get(filter, orderBy);
total = query.Count();
query = skipCount > ? query.Skip(skipCount).Take(size) : query.Take(size);
return query.ToList();
} public IList<TEntity> GetPaged<TEntity>(out int total, Expression<Func<TEntity, bool>> filter = null, string orderBy = null, int index = , int size = ) where TEntity : class
{
int skipCount = (index - ) * size;
var query = Get(filter, orderBy);
total = query.Count();
query = skipCount > ? query.Skip(skipCount).Take(size) : query.Take(size);
return query.ToList();
} public IQueryable<TEntity> Get<TEntity>(Expression<Func<TEntity, bool>> filter = null, string orderBy = null) where TEntity : class
{
IQueryable<TEntity> query = dbContext.Set<TEntity>();
if (filter != null)
{
query = query.Where(filter);
}
if (!string.IsNullOrEmpty(orderBy))
{
query = query.OrderBy(orderBy);
}
return query.AsQueryable();
} public IQueryable<TEntity> Get<TEntity>(Expression<Func<TEntity, bool>> filter = null, Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null) where TEntity : class
{
IQueryable<TEntity> query = dbContext.Set<TEntity>();
if (filter != null)
{
query = query.Where(filter);
}
if (orderBy != null)
{
orderBy(query).AsQueryable();
}
return query.AsQueryable();
} #endregion #region 私有方法 private int Save()
{
int effect = ;
if (!this.IsTransaction)
{
effect = dbContext.SaveChanges();
}
return effect;
} /// <summary>
/// 变更上下文管理器(对象)
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <param name="model"></param>
/// <param name="state"></param>
private int ChangeObjectState<TEntity>(TEntity model, EntityState state) where TEntity : class
{
//_context.Configuration.ValidateOnSaveEnabled = false;
dbContext.Entry<TEntity>(model).State = state;
return Save(); } /// <summary>
/// 变更上下文管理器(对象集合)
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <param name="model"></param>
/// <param name="state"></param>
private int ChangeObjectState<TEntity>(IEnumerable<TEntity> model, EntityState state) where TEntity : class
{
if (model == null) return ; //_context.Configuration.AutoDetectChangesEnabled = false;
model.ToList().ForEach(p => dbContext.Entry<TEntity>(p).State = state);
return Save(); } #endregion /// <summary>
/// 执行带参数的sql语句,返回List
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="strsql"></param>
/// <param name="paras"></param>
/// <returns></returns>
public IEnumerable<T> GetList<T>(string strsql, SqlParameter[] paras)
{
return dbContext.Database.SqlQuery<T>(strsql, paras).ToList();
} /// <summary>
/// 执行不带参数的sql语句,返回list
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="strsql"></param>
/// <returns></returns>
public IEnumerable<T> GetList<T>(string strsql)
{
return dbContext.Database.SqlQuery<T>(strsql).ToList();
} /// <summary>
/// 执行带参数的sql语句,返回一个对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="strsql"></param>
/// <param name="paras"></param>
/// <returns></returns>
public T GetOneEntity<T>(string strsql, SqlParameter[] paras)
{
return dbContext.Database.SqlQuery<T>(strsql, paras).Cast<T>().First();
} /// <summary>
/// 执行不带参数的sql语句,返回一个对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="strsql"></param>
/// <returns></returns>
public T GetOneEntity<T>(string strsql)
{
return dbContext.Database.SqlQuery<T>(strsql).Cast<T>().First();
} public int ExecuteSqlCommand(string sql, params SqlParameter[] paras)
{
if (this.IsTransaction)
{
if (dbContext.Database.CurrentTransaction == null)
{
dbContext.Database.BeginTransaction();
}
}
return dbContext.Database.ExecuteSqlCommand(sql, paras);
} /// <summary>
/// 获取查询数量
/// </summary>
/// <param name="sql"></param>
/// <param name="paras"></param>
/// <returns></returns>
public int GetCount(string sql, SqlParameter[] paras)
{
return dbContext.Database.SqlQuery(typeof(int), sql, paras).Cast<int>().First();
} public void BeginTransaction()
{
this.IsTransaction = true; } public int Commit()
{
int reault = dbContext.SaveChanges();
this.IsTransaction = false;
DbContextTransaction transaction = dbContext.Database.CurrentTransaction;
if (transaction != null)
{
transaction.Commit();
transaction.Dispose();
reault += ;
} return reault;
} public void Rollback()
{
this.IsTransaction = false;
DbContextTransaction transaction = dbContext.Database.CurrentTransaction;
if (transaction != null)
{
transaction.Rollback();
transaction.Dispose();
} } public bool IsTransaction
{
get;
private set;
} public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
} public virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
this.dbContext.Dispose();
}
}
this.disposed = true;
}
}

Entity Framework 第一篇的更多相关文章

  1. Entity Framework 第二篇 事务

    Entity Framework  事务 结合第一篇的代码 public class BaseRepository : ITransaction, IDisposable { private XFDb ...

  2. (Entity framework 应用篇)把权限判断封装在数据库访问层

    这里,我只是以一个例子,说一下简单权限控制,通过这个例子,大家可以设计庞大的权限管理层,把权限控制封装到数据库访问层,这样程序员就不用再写权限判断的代码了 首先,先看看我数据库DBContext的定义 ...

  3. Entity Framework 第九篇 关于自增列的事务处理

    如果一个表带有自增列的,那么在事务处理的过程中,如果抑制了提交,自增的序号就不会得到,如果我们需要得到那怎么办呢?可以临时提交,但是既然提交了就要考虑到事务回滚,否则无法满足数据的一致性 public ...

  4. Entity Framework的启动速度优化

    最近开发的服务放到IIS上寄宿之后,遇到一些现象,比如刚部署之后,第一次启动很慢:程序放置一会儿,再次请求也会比较慢.比如第一个问题,可以解释为初次请求某一个服务的时候,需要把程序集加载到内存中可能比 ...

  5. Code First :使用Entity. Framework编程(8) ----转发 收藏

    第8章 Code First将走向哪里? So far, this book has covered all of the Code First components that reached the ...

  6. Entity Framework 6.0 入门系列 第一篇

    Entity Framework 6.0 入门系列 第一篇 好几年前接触过一些ef感觉不是很好用,废弃.但是 Entity Framework 6.0是经过几个版本优化过的产物,性能和功能不断完善,开 ...

  7. 第一篇 Entity Framework Plus 之 Audit

    一般系统会有登陆日志,操作日志,异常日志,已经满足大部分的需求了.但是有时候,还是需要Audit 审计日志,审计日志,主要针对数据增,改,删操作数据变化的记录,主要是对数据变化的一个追踪过程.其中主要 ...

  8. 第一篇:Entity Framework 简介

    先从ORM说起吧,很多年前,由于.NET的开源组件不像现在这样发达,更别说一个开源的ORM框架,出于项目需要,以及当时OOP兴起(总不至于,在项目里面全是SQL语句),就自己开始写ORM框架.要开发O ...

  9. 第三篇 Entity Framework Plus 之 Query Cache

    离上一篇博客,快一周,工作太忙,只能利用休息日来写一些跟大家分享,Entity Framework Plus 组件系列文章,之前已经写过两篇 第一篇 Entity Framework Plus 之 A ...

随机推荐

  1. sql xml 入门

    /*sql xml 入门:    --by jinjazz    --http://blog.csdn.net/jinjazz        1.xml:        能认识元素.属性和值      ...

  2. 有趣的linux命令

    安装工具 debian => apt-get (In Debian like OS) red hat=> yum -y (In Red Hat like OS) mac => bre ...

  3. 如何学习c++

    在之后的随笔中,我作为一个c++的初学者将会把我如何学习c++的经历尽可能详细的记录下来. 这里引用了JerryZhang在他的博文里面写的一段话,当作我的座右铭. 1.多交流:不管你的技术多么硬,你 ...

  4. 夺命雷公狗---Thinkphp----5之数据库的链接

    我们打开WEB目录下发现了Common和Home以及Runtime这三个文件夹 那么我们第一个目标是完成网站后台的首页吧,那么我们就直接将Home的文件夹复制一份出来,并且改名为Admin这样就可以分 ...

  5. MOPSO 多目标例子群优化算法

    近年来,基于启发式的多目标优化技术得到了很大的发展,研究表明该技术比经典方法更实用和高效.有代表性的多目标优化算法主要有NSGA.NSGA-II.SPEA.SPEA2.PAES和PESA等.粒子群优化 ...

  6. java 与 R 相互调用

    https://www.r-project.org/ http://cos.name/2013/08/r-rjava-java/ http://blog.csdn.net/hwssg/article/ ...

  7. 搞不定linux下的无线网卡驱动的权宜之计

    毕竟windows用了这么些年了,对windows下的一些东西也比较熟悉,还有就是windows的软件方式比较傻瓜. 在linux下搞不定无线网卡啊,幸亏有甲骨文的virtualbox,咱虚拟一个xp ...

  8. ipseccmd命令解析

    IPSec 首先需要指出的是,IPSec和TCP/IP筛选是不同的东西,大家不要混淆了.TCP/IP筛选的功能十分有限,远不如IPSec灵活和强大.下面就说说如何在命令行下控制IPSec. XP系统用 ...

  9. java设置环境变量小工具

    unit MainUnit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Fo ...

  10. 怎样使用AutoLayOut为UIScrollView添加约束

    1.在ViewController中拖入1个UIScrollView,并为其添加约束 约束为上下左右四边与superview对齐 2.在scrollview中,拖入1个UIView,为了便于区分将其设 ...