EF实体框架数据操作基类主要是规范增、改、查、分页、Lambda表达式条件处理,以及异步操作等特性,这样能够尽可能的符合基类这个特殊类的定义,实现功能接口的最大化重用和统一。
1、程序代码
/// <summary>
/// MSSQL数据库 数据层的父类
/// </summary>
/// <typeparam name="T"></typeparam>
public class BaseDAL<T> where T : class
{
//EF上下文
private readonly DbContext _db;
#region 00 单例模式 private static BaseDAL<T> _mInstance = null;
private static object obj = new object(); public BaseDAL(DbContext db)
{
_db = db;
} public static BaseDAL<T> ManagerContent(DbContext dbContext)
{
if (_mInstance == null)
{
lock (obj)
{
_mInstance = new BaseDAL<T>(dbContext);
}
}
return _mInstance;
} #endregion
00 单例模式
#region 1.0 新增 实体 +int Add(T model)
/// <summary>
/// 新增 实体
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public bool Add(T model)
{
try
{
_db.Set<T>().Add(model);
_db.SaveChanges();
//保存成功后,会将自增的id设置给 model的 主键属性,并返回受影响行数
}
catch (EntityException ex)
{
LogHelper.Error("Add", ex);
LogHelper.Error(ex.Message); throw ex.InnerException;
}
catch (DbException exc)
{
LogHelper.Error("Add", exc);
throw exc.InnerException;
}
return true;
}
#endregion
1.0 新增 实体 +int Add(T model)
#region 2.0 根据 id 删除 +bool Del(T model)
/// <summary>
/// 根据 id 删除
/// </summary>
/// <param name="model">包含要删除id的对象</param>
/// <returns></returns>
public bool Del(T model)
{
try
{
_db.Set<T>().Attach(model);
_db.Set<T>().Remove(model);
_db.SaveChanges();
}
catch (EntityException ex)
{
LogHelper.Error("Add", ex);
LogHelper.Error(ex.Message); throw ex.InnerException;
}
catch (DbException exc)
{
LogHelper.Error("Add", exc);
throw exc.InnerException;
}
return true;
}
#endregion
2.0 根据 id 删除 +bool Del(T model)
#region 3.0 根据条件删除 +bool DelBy(Expression<Func<T, bool>> delWhere)
/// <summary>
/// 3.0 根据条件删除
/// </summary>
/// <param name="delWhere"></param>
/// <returns></returns>
public bool DelBy(Expression<Func<T, bool>> delWhere)
{
try
{
//3.1查询要删除的数据
List<T> listDeleting = _db.Set<T>().Where(delWhere).ToList();
//3.2将要删除的数据 用删除方法添加到 EF 容器中
listDeleting.ForEach(u =>
{
_db.Set<T>().Attach(u);//先附加到 EF容器
_db.Set<T>().Remove(u);//标识为 删除 状态
});
//3.3一次性 生成sql语句到数据库执行删除
_db.SaveChanges();
}
catch (EntityException ex)
{
LogHelper.Error("Add", ex);
LogHelper.Error(ex.Message); throw ex.InnerException;
}
catch (DbException exc)
{
LogHelper.Error("Add", exc);
throw exc.InnerException;
}
return true;
}
#endregion
3.0 根据条件删除 +bool DelBy(Expression<Func<T, bool>> delWhere)
#region 4.0 修改 +bool Modify(T model, params string[] proNames)
/// <summary>
/// 4.0 修改,如:
/// T u = new T() { uId = 1, uLoginName = "asdfasdf" };
/// this.Modify(u, "uLoginName");
/// </summary>
/// <param name="model">要修改的实体对象</param>
/// <param name="proNames">要修改的 属性 名称</param>
/// <returns></returns>
public bool Modify(T model, params string[] proNames)
{
try
{
//4.1将 对象 添加到 EF中
DbEntityEntry entry = _db.Entry<T>(model);
//4.2先设置 对象的包装 状态为 Unchanged
entry.State = EntityState.Unchanged;
//4.3循环 被修改的属性名 数组
foreach (string proName in proNames)
{
//4.4将每个 被修改的属性的状态 设置为已修改状态;后面生成update语句时,就只为已修改的属性 更新
entry.Property(proName).IsModified = true;
}
//4.4一次性 生成sql语句到数据库执行
_db.SaveChanges();
}
catch (EntityException ex)
{
LogHelper.Error("Add", ex);
LogHelper.Error(ex.Message); throw ex.InnerException;
}
catch (DbException exc)
{
LogHelper.Error("Add", exc);
throw exc.InnerException;
} return true;
}
#endregion
4.0 修改 +bool Modify(T model, params string[] proNames)
#region 4.1 批量修改 +bool Modify(T model, Expression<Func<T, bool>> whereLambda, params string[] modifiedProNames)
/// <summary>
/// 4.0 批量修改
/// </summary>
/// <param name="model">要修改的实体对象</param>
/// <param name="whereLambda">查询条件</param>
/// <param name="modifiedProNames">要修改的 属性 名称</param>
/// <returns></returns>
public bool ModifyBy(T model, Expression<Func<T, bool>> whereLambda, params string[] modifiedProNames)
{
try
{
//4.1查询要修改的数据
List<T> listModifing = _db.Set<T>().Where(whereLambda).ToList(); //获取 实体类 类型对象
Type t = typeof(T); // model.GetType();
//获取 实体类 所有的 公有属性
List<PropertyInfo> proInfos = t.GetProperties(BindingFlags.Instance | BindingFlags.Public).ToList();
//创建 实体属性 字典集合
Dictionary<string, PropertyInfo> dictPros = new Dictionary<string, PropertyInfo>();
//将 实体属性 中要修改的属性名 添加到 字典集合中 键:属性名 值:属性对象
proInfos.ForEach(p =>
{
if (modifiedProNames.Contains(p.Name))
{
dictPros.Add(p.Name, p);
}
}); //4.3循环 要修改的属性名
foreach (string proName in modifiedProNames)
{
//判断 要修改的属性名是否在 实体类的属性集合中存在
if (dictPros.ContainsKey(proName))
{
//如果存在,则取出要修改的 属性对象
PropertyInfo proInfo = dictPros[proName];
//取出 要修改的值
object newValue = proInfo.GetValue(model, null); //object newValue = model.uName; //4.4批量设置 要修改 对象的 属性
foreach (T usrO in listModifing)
{
//为 要修改的对象 的 要修改的属性 设置新的值
proInfo.SetValue(usrO, newValue, null); //usrO.uName = newValue;
}
}
}
//4.4一次性 生成sql语句到数据库执行
_db.SaveChanges();
}
catch (EntityException ex)
{
LogHelper.Error("Add", ex);
LogHelper.Error(ex.Message); throw ex.InnerException;
}
catch (DbException exc)
{
LogHelper.Error("Add", exc);
throw exc.InnerException;
} return true;
}
#endregion
4.1 批量修改 +bool Modify(T model, Expression<Func<T, bool>> whereLambda, params string[] modifiedProNames)
#region 4.2 修改个单个实体
public bool Modify(T model)
{
try
{
_db.Entry(typeof (T)).State = EntityState.Modified;
//4.4一次性 生成sql语句到数据库执行
_db.SaveChanges();
}
catch (EntityException ex)
{
LogHelper.Error("Add", ex);
LogHelper.Error(ex.Message); throw ex.InnerException;
}
catch (DbException exc)
{
LogHelper.Error("Add", exc);
throw exc.InnerException;
} return true;
}
#endregion
4.2 修改个单个实体
#region 5.0 根据条件查询 +IQueryable<T> GetListBy(Expression<Func<T,bool>> whereLambda)
/// <summary>
/// 5.0 根据条件查询 +List<T> GetListBy(Expression<Func<T,bool>> whereLambda)
/// </summary>
/// <param name="whereLambda">Lambda表达式</param>
/// <returns></returns>
public IQueryable<T> GetListBy(Expression<Func<T, bool>> whereLambda)
{
try
{
return _db.Set<T>().Where(whereLambda);
}
catch (EntityException ex)
{
LogHelper.Error("Add", ex);
LogHelper.Error(ex.Message); throw ex.InnerException;
}
catch (DbException exc)
{
LogHelper.Error("Add", exc);
throw exc.InnerException;
}
}
#endregion
5.0 根据条件查询 +IQueryable GetListBy(Expression<Func<T,bool>> whereLambda)
#region 5.1 根据条件 排序 和查询 + IQueryable<T> GetListBy<TKey>
/// <summary>
/// 5.1 根据条件 排序 和查询
/// </summary>
/// <typeparam name="TKey">排序字段类型</typeparam>
/// <param name="whereLambda">查询条件 lambda表达式</param>
/// <param name="orderLambda">排序条件 lambda表达式</param>
/// <returns></returns>
public IQueryable<T> GetListBy<TKey>(Expression<Func<T, bool>> whereLambda, Expression<Func<T, TKey>> orderLambda)
{
try
{
return _db.Set<T>().Where(whereLambda).OrderBy(orderLambda);
}
catch (EntityException ex)
{
LogHelper.Error("Add", ex);
LogHelper.Error(ex.Message); throw ex.InnerException;
}
catch (DbException exc)
{
LogHelper.Error("Add", exc);
throw exc.InnerException;
}
}
#endregion
5.1 根据条件 排序 和查询 + IQueryable GetListBy
#region 5.2 根据条件查询 返回单条数据 T GetEntity(Expression<Func<T, bool>> whereLambda) public T GetEntity(Expression<Func<T, bool>> whereLambda)
{
try
{
return _db.Set<T>().First(whereLambda);
}
catch (EntityException ex)
{
LogHelper.Error("Add", ex);
LogHelper.Error(ex.Message); throw ex.InnerException;
}
catch (DbException exc)
{
LogHelper.Error("Add", exc);
throw exc.InnerException;
}
}
#endregion
5.2 根据条件查询 返回单条数据 T GetEntity(Expression<Func<T, bool>> whereLambda)
#region 6.0 分页查询 + IQueryable<T> GetPagedList<TKey>
/// <summary>
/// 6.0 分页查询 + IQueryable<T> GetPagedList<TKey>
/// </summary>
/// <param name="pageIndex">页码</param>
/// <param name="pageSize">页容量</param>
/// <param name="whereLambda">条件 lambda表达式</param>
/// <param name="orderBy">排序 lambda表达式</param>
/// <returns></returns>
public IQueryable<T> GetPagedList<TKey>(int pageIndex, int pageSize, Expression<Func<T, bool>> whereLambda, Expression<Func<T, TKey>> orderBy)
{
// 分页 一定注意: Skip 之前一定要 OrderBy
try
{
return _db.Set<T>().Where(whereLambda).OrderBy(orderBy).Skip((pageIndex - ) * pageSize).Take(pageSize);
}
catch (EntityException ex)
{
LogHelper.Error("Add", ex);
LogHelper.Error(ex.Message); throw ex.InnerException;
}
catch (DbException exc)
{
LogHelper.Error("Add", exc);
throw exc.InnerException;
}
}
#endregion
6.0 分页查询 + IQueryable GetPagedList
#region 7.0执行SQL+string ExecMaxValueSql()
public string ExecMaxValueSql()
{
string sql = @"begin tran
DECLARE @Value bigint
update " + typeof(T).Name + @"
set value = value+1;
select @Value = value from " + typeof(T).Name + @";
select cast(@Value as varchar(10));
commit tran";
string value = _db.Database.SqlQuery<string>(sql).First(); return value;
}
#endregion
7.0执行SQL+string ExecMaxValueSql()
}
2、 日志记录组件采用 Log4Net
public class LogHelper
{
private static readonly log4net.ILog Log = log4net.LogManager.GetLogger("ApplicationLog");
public static void Info(string info)
{
Log.Info(info);
}
public static void Info(string info, Exception ex)
{
Log.Info(info, ex);
}
public static void Error(string info, Exception ex)
{
Log.Info(info, ex);
}
public static void Error(string info)
{
Log.Error(info);
}
public void Debug(string info)
{
Log.Debug(info);
}
public void Debug(string info, Exception se)
{
Log.Debug(info, se);
}
public void Warn(string info)
{
Log.Warn(info);
}
public void Warn(string info, Exception ex)
{
Log.Warn(info, ex);
}
public void Fatal(string info)
{
Log.Fatal(info);
}
public void Fatal(string info, Exception ex)
{
Log.Fatal(info, ex);
}
}
日志记录
<?xml version="1.0" encoding="utf-8" ?>
<log4net>
<logger name="ApplicationLog">
<level value="INFO" />
<appender-ref ref="rollingFile" />
</logger> <appender name="rollingFile" type="log4net.Appender.RollingFileAppender, log4net" >
<param name="File" value="ServiceLog.txt" />
<param name="AppendToFile" value="true" />
<param name="RollingStyle" value="Date" />
<param name="MaximumFileSize" value="5MB"></param>
<param name="DatePattern" value="_yyyy.MM.dd" />
<param name="StaticLogFileName" value="true" />
<layout type="log4net.Layout.PatternLayout, log4net">
<param name="ConversionPattern" value="%d - %m%n" />
</layout>
</appender>
</log4net>
配置文件