这段时间研究了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. [转]30分钟学会反向Ajax

    原文链接:http://www.cnblogs.com/learnhow/p/5708364.html 场景1:当有新邮件的时候,网页自动弹出提示信息而无需用户手动的刷新收件箱. 场景2:当用户的手机 ...

  2. paper 43 :ENDNOTE下载及使用方法简介

    转载来源:http://blog.sciencenet.cn/blog-484734-367968.html 软件下载来源: EndNote v9.0 Final 正式版:http://www.ttd ...

  3. 夺命雷公狗---Thinkphp----2之快快速搭建TP环境

    <?php //定义项目目录 define('APP_PATH','./WEB/'); //开启调试 define('APP_DEBUG',True); //包含thinkphp项目入口文件 r ...

  4. Android真机测试 INSTALL_FAILED_INSUFFICIENT_STORAGE 解决方法[转]

    方法一: 试试修改一下manifest文件 :添加 一句:   android:installLocation="preferExternal" [html]view plainc ...

  5. Ado.net连接池 sp_reset_connection 概念

    什么是连接池? 正常情况下,每次访问数据库都会打开和关闭,中断物理连接后需要再次进行物理连接.这样操作会浪费资源 使用连接池,主要的区别在于,不需要中断物理连接,即每次中断请求时spid还是存在! 原 ...

  6. html5,表格与框架综合布局

    <!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8&qu ...

  7. 用jQuery创建HTML中不存在的标签元素碰到的问题

    如果你自定义了一个标签,比如<aaa></aaa> 用jQuery的写法,比如var custom_element = $('<aaa class="ee&qu ...

  8. Asp.net的post提交方式

    //建立WebRequest对象,url目标地址HttpWebRequest req =(HttpWebRequest)WebRequest.Create(url); //将LoginInfo转换为b ...

  9. :not(selector)

    描述: 用于筛选的选择器 查找所有未选中的 input 元素 HTML 代码: <input name="apple" /> <input name=" ...

  10. Linux 的 Crontab 命令运用(转)

    cron来源于希腊单词chronos(意为“时间”),是linux系统下一个自动执行指定任务的程序.例如,你想在每晚睡觉期间创建某些文件或文件夹的备份,就可以用cron来自动执行. 服务的启动和停止 ...