Entity Framework 第一篇
这段时间研究了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 第一篇的更多相关文章
- Entity Framework 第二篇 事务
Entity Framework 事务 结合第一篇的代码 public class BaseRepository : ITransaction, IDisposable { private XFDb ...
- (Entity framework 应用篇)把权限判断封装在数据库访问层
这里,我只是以一个例子,说一下简单权限控制,通过这个例子,大家可以设计庞大的权限管理层,把权限控制封装到数据库访问层,这样程序员就不用再写权限判断的代码了 首先,先看看我数据库DBContext的定义 ...
- Entity Framework 第九篇 关于自增列的事务处理
如果一个表带有自增列的,那么在事务处理的过程中,如果抑制了提交,自增的序号就不会得到,如果我们需要得到那怎么办呢?可以临时提交,但是既然提交了就要考虑到事务回滚,否则无法满足数据的一致性 public ...
- Entity Framework的启动速度优化
最近开发的服务放到IIS上寄宿之后,遇到一些现象,比如刚部署之后,第一次启动很慢:程序放置一会儿,再次请求也会比较慢.比如第一个问题,可以解释为初次请求某一个服务的时候,需要把程序集加载到内存中可能比 ...
- Code First :使用Entity. Framework编程(8) ----转发 收藏
第8章 Code First将走向哪里? So far, this book has covered all of the Code First components that reached the ...
- Entity Framework 6.0 入门系列 第一篇
Entity Framework 6.0 入门系列 第一篇 好几年前接触过一些ef感觉不是很好用,废弃.但是 Entity Framework 6.0是经过几个版本优化过的产物,性能和功能不断完善,开 ...
- 第一篇 Entity Framework Plus 之 Audit
一般系统会有登陆日志,操作日志,异常日志,已经满足大部分的需求了.但是有时候,还是需要Audit 审计日志,审计日志,主要针对数据增,改,删操作数据变化的记录,主要是对数据变化的一个追踪过程.其中主要 ...
- 第一篇:Entity Framework 简介
先从ORM说起吧,很多年前,由于.NET的开源组件不像现在这样发达,更别说一个开源的ORM框架,出于项目需要,以及当时OOP兴起(总不至于,在项目里面全是SQL语句),就自己开始写ORM框架.要开发O ...
- 第三篇 Entity Framework Plus 之 Query Cache
离上一篇博客,快一周,工作太忙,只能利用休息日来写一些跟大家分享,Entity Framework Plus 组件系列文章,之前已经写过两篇 第一篇 Entity Framework Plus 之 A ...
随机推荐
- SLF4简介
The Simple Logging Facade for Java (SLF4J) serves as a simple facade or abstraction for various logg ...
- [原创]java WEB学习笔记68:Struts2 学习之路-- 类型转换与复杂属性配合使用
本博客的目的:①总结自己的学习过程,相当于学习笔记 ②将自己的经验分享给大家,相互学习,互相交流,不可商用 内容难免出现问题,欢迎指正,交流,探讨,可以留言,也可以通过以下方式联系. 本人互联网技术爱 ...
- yii框架中保存第三方登录信息
(第三方登录) 创建应用,域名,详情请看:http://www.cnblogs.com/xujn/p/5287157.html 效果图:
- cocos2d-x游戏开发之烟花粒子效果
//散烟花及“太”“棒”“了”效果 void mygame::playfire() { sprite *tai = sprite::create("tai.png"); tai-& ...
- sql xml 入门
/*sql xml 入门: --by jinjazz --http://blog.csdn.net/jinjazz 1.xml: 能认识元素.属性和值 ...
- SQL SERVER2000中订阅与发布的具体操作
同步过程 一.准备工作,如果完成则可跳过. 1.内网DB服务器作为发布服务器,外网DB服务器作为订阅服务器. 发布服务器和订阅服务器上分别创建Windows用户jl,密码jl,隶属于administr ...
- JavaScript:九种弹出对话框
[1.最基本的js弹出对话框窗口代码] 这是最基本的js弹出对话框,其实代码就几句非常简单: <script LANGUAGE="javascript"> <!- ...
- postgres创建用户,表
使用createuser来创建用户 [postgres@web1 ~]$ /data/pgsql/bin/createuser --help createuser creates a new Post ...
- CentOS6.5系统软件仓库及挂载NTFS
第一步:下载rpmforge,下载对应的版本,就是对应CentOS版本,还有32位与64位也要对应上.rpmforge拥有4000多种CentOS的软件包,被CentOS社区认为是最安全也是最稳定的一 ...
- Linux查看CPU和内存使用情况【转】
转自:http://www.cnblogs.com/xd502djj/archive/2011/03/01/1968041.html 在系统维护的过程中,随时可能有需要查看 CPU 使用率,并根据相应 ...