entity framework 6 自己編寫的通用資料類
阿新 • • 發佈:2019-02-18
public class BaseDAL { string strConn = ""; public BaseDAL(string connString) { strConn = connString; } #region 通用增刪改查 #region 非原始sql語句方式 /// <summary> /// 新增 /// </summary> /// <param name="entity">實體</param> /// <returns>返回受影響行數</returns> public bool Add<T>(T entity) where T : class { using (SysDb<T> db = new SysDb<T>(strConn)) { db.Entry<T>(entity).State = EntityState.Added; return db.SaveChanges() > 0; } } /// <summary> /// 修改 /// </summary> /// <param name="entity">實體</param> /// <returns>返回受影響行數</returns> public bool Update<T>(T entity) where T : class { using (SysDb<T> db = new SysDb<T>(strConn)) { db.Set<T>().Attach(entity); db.Entry<T>(entity).State = EntityState.Modified; return db.SaveChanges() > 0; } } /// <summary> /// 刪除 /// </summary> /// <param name="entity">實體</param> /// <returns>返回受影響行數</returns> public bool Delete<T>(T entity) where T : class { using (SysDb<T> db = new SysDb<T>(strConn)) { db.Set<T>().Attach(entity); db.Entry<T>(entity).State = EntityState.Deleted; return db.SaveChanges() > 0; } } /// <summary> /// 根據條件刪除 /// </summary> /// <param name="deleWhere">刪除條件</param> /// <returns>返回受影響行數</returns> public bool DeleteByConditon<T>(Expression<Func<T, bool>> deleWhere) where T : class { using (SysDb<T> db = new SysDb<T>(strConn)) { List<T> entitys = db.Set<T>().Where(deleWhere).ToList(); entitys.ForEach(m => db.Entry<T>(m).State = EntityState.Deleted); return db.SaveChanges() > 0; } } /// <summary> /// 查詢單個 /// </summary> /// <param name="id">主鍵</param> /// <returns></returns> public T GetSingleById<T>(int id) where T : class { using (SysDb<T> db = new SysDb<T>(strConn)) { return db.Set<T>().Find(id); } } /// <summary> /// 查詢單個 /// </summary> /// <param name="seleWhere">查詢條件</param> /// <returns></returns> public T GetSingle<T>(Expression<Func<T, bool>> seleWhere) where T : class { using (SysDb<T> db = new SysDb<T>(strConn)) { return db.Set<T>().AsExpandable().FirstOrDefault(seleWhere); } } /// <summary> /// 獲取所有實體集合 /// </summary> /// <returns></returns> public List<T> GetAll<T>() where T : class { using (SysDb<T> db = new SysDb<T>(strConn)) { return db.Set<T>().AsExpandable().ToList<T>(); } } /// <summary> /// 獲取所有實體集合(單個排序) /// </summary> /// <returns></returns> public List<T> GetAll<T, Tkey>(Expression<Func<T, Tkey>> orderWhere, bool isDesc) where T : class { using (SysDb<T> db = new SysDb<T>(strConn)) { return CommonSort(db.Set<T>().AsExpandable(), orderWhere, isDesc).ToList<T>(); } } /// <summary> /// 獲取所有實體集合(多個排序) /// </summary> /// <returns></returns> public List<T> GetAll<T>(params OrderModelField[] orderByExpression) where T : class { using (SysDb<T> db = new SysDb<T>(strConn)) { return CommonSort(db.Set<T>().AsExpandable(), orderByExpression).ToList(); } } /// <summary> /// 單個排序通用方法 /// </summary> /// <typeparam name="Tkey">排序欄位</typeparam> /// <param name="data">要排序的資料</param> /// <param name="orderWhere">排序條件</param> /// <param name="isDesc">是否倒序</param> /// <returns>排序後的集合</returns> public IQueryable<T> CommonSort<T, Tkey>(IQueryable<T> data, Expression<Func<T, Tkey>> orderWhere, bool isDesc) where T : class { if (isDesc) { return data.OrderByDescending(orderWhere); } else { return data.OrderBy(orderWhere); } } /// <summary> /// 多個排序通用方法 /// </summary> /// <typeparam name="Tkey">排序欄位</typeparam> /// <param name="data">要排序的資料</param> /// <param name="orderWhereAndIsDesc">字典集合(排序條件,是否倒序)</param> /// <returns>排序後的集合</returns> public IQueryable<T> CommonSort<T>(IQueryable<T> data, params OrderModelField[] orderByExpression) where T : class { //建立表示式變數引數 var parameter = Expression.Parameter(typeof(T), "o"); if (orderByExpression != null && orderByExpression.Length > 0) { for (int i = 0; i < orderByExpression.Length; i++) { //根據屬性名獲取屬性 var property = typeof(T).GetProperty(orderByExpression[i].PropertyName); //建立一個訪問屬性的表示式 var propertyAccess = Expression.MakeMemberAccess(parameter, property); var orderByExp = Expression.Lambda(propertyAccess, parameter); string OrderName = ""; if (i > 0) { OrderName = orderByExpression[i].IsDESC ? "ThenByDescending" : "ThenBy"; } else OrderName = orderByExpression[i].IsDESC ? "OrderByDescending" : "OrderBy"; MethodCallExpression resultExp = Expression.Call(typeof(Queryable), OrderName, new Type[] { typeof(T), property.PropertyType }, data.Expression, Expression.Quote(orderByExp)); data = data.Provider.CreateQuery<T>(resultExp); } } return data; } /// <summary> /// 根據條件查詢實體集合 /// </summary> /// <param name="seleWhere">查詢條件 lambel表示式</param> /// <returns></returns> public List<T> GetList<T>(Expression<Func<T, bool>> seleWhere) where T : class { using (SysDb<T> db = new SysDb<T>(strConn)) { return db.Set<T>().AsExpandable().Where(seleWhere).ToList(); } } /// <summary> /// 根據條件查詢實體集合 /// </summary> /// <param name="seleWhere">查詢條件 lambel表示式</param> /// <returns></returns> public List<T> GetList<T, TValue>(Expression<Func<T, TValue>> seleWhere, IEnumerable<TValue> conditions) where T : class { using (SysDb<T> db = new SysDb<T>(strConn)) { return db.Set<T>().AsExpandable().WhereIn<T, TValue>(seleWhere, conditions).ToList(); } } /// <summary> /// 根據條件查詢實體集合(單個欄位排序) /// </summary> /// <param name="seleWhere">查詢條件 lambel表示式</param> /// <returns></returns> public List<T> GetList<T, Tkey>(Expression<Func<T, bool>> seleWhere, Expression<Func<T, Tkey>> orderWhere, bool isDesc) where T : class { using (SysDb<T> db = new SysDb<T>(strConn)) { return CommonSort(db.Set<T>().AsExpandable().Where(seleWhere), orderWhere, isDesc).ToList(); } } /// <summary> /// 根據條件查詢實體集合(多個欄位排序) /// </summary> /// <param name="seleWhere">查詢條件 lambel表示式</param> /// <returns></returns> public List<T> GetList<T>(Expression<Func<T, bool>> seleWhere, params OrderModelField[] orderByExpression) where T : class { using (SysDb<T> db = new SysDb<T>(strConn)) { return CommonSort(db.Set<T>().AsExpandable().Where(seleWhere), orderByExpression).ToList(); } } /// <summary> /// 獲取分頁集合(無條件無排序) /// </summary> /// <returns></returns> public List<T> GetListPaged<T, Tkey>(int pageIndex, int pageSize, out int totalcount) where T : class { using (SysDb<T> db = new SysDb<T>(strConn)) { totalcount = db.Set<T>().AsExpandable().Count();//獲取總數 //需要增加AsExpandable(),否則查詢的是所有資料到記憶體,然後再排序 AsExpandable是linqkit.dll中的方法 return db.Set<T>().AsExpandable().Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList(); } } /// <summary> /// 獲取分頁集合(無條件單個排序) /// </summary> /// <returns></returns> public List<T> GetListPaged<T, Tkey>(int pageIndex, int pageSize, Expression<Func<T, Tkey>> orderWhere, bool isDesc, out int totalcount) where T : class { using (SysDb<T> db = new SysDb<T>(strConn)) { totalcount = db.Set<T>().AsExpandable().Count();//獲取總數 //需要增加AsExpandable(),否則查詢的是所有資料到記憶體,然後再排序 AsExpandable是linqkit.dll中的方法 return CommonSort(db.Set<T>().AsExpandable(), orderWhere, isDesc).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList(); } } /// <summary> /// 獲取分頁集合(無條件多欄位排序) /// </summary> /// <returns></returns> public List<T> GetListPaged<T>(int pageIndex, int pageSize, out int totalcount, params OrderModelField[] orderByExpression) where T : class { using (SysDb<T> db = new SysDb<T>(strConn)) { totalcount = db.Set<T>().AsExpandable().Count();//獲取總數 //需要增加AsExpandable(),否則查詢的是所有資料到記憶體,然後再排序 AsExpandable是linqkit.dll中的方法 return CommonSort(db.Set<T>().AsExpandable(), orderByExpression).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList(); } } /// <summary> /// 獲取分頁集合(有條件無排序) /// </summary> /// <returns></returns> public List<T> GetListPaged<T, Tkey>(int pageIndex, int pageSize, Expression<Func<T, bool>> seleWhere, out int totalcount) where T : class { using (SysDb<T> db = new SysDb<T>(strConn)) { totalcount = db.Set<T>().AsExpandable().Where(seleWhere).Count();//獲取總數 //需要增加AsExpandable(),否則查詢的是所有資料到記憶體,然後再排序 AsExpandable是linqkit.dll中的方法 return db.Set<T>().AsExpandable().Where(seleWhere).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList(); } } /// <summary> /// 獲取分頁集合(有條件單個排序) /// </summary> /// <returns></returns> public List<T> GetListPaged<T, Tkey>(int pageIndex, int pageSize, Expression<Func<T, bool>> seleWhere, Expression<Func<T, Tkey>> orderWhere, bool isDesc, out int totalcount) where T : class { using (SysDb<T> db = new SysDb<T>(strConn)) { totalcount = db.Set<T>().AsExpandable().Where(seleWhere).Count();//獲取總數 //需要增加AsExpandable(),否則查詢的是所有資料到記憶體,然後再排序 AsExpandable是linqkit.dll中的方法 return CommonSort(db.Set<T>().AsExpandable().Where(seleWhere), orderWhere, isDesc).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList(); } } /// <summary> /// 獲取分頁集合(有條件多欄位排序) /// </summary> /// <returns></returns> public List<T> GetListPaged<T>(int pageIndex, int pageSize, Expression<Func<T, bool>> seleWhere, out int totalcount, params OrderModelField[] orderModelFiled) where T : class { using (SysDb<T> db = new SysDb<T>(strConn)) { totalcount = db.Set<T>().AsExpandable().Where(seleWhere).Count();//獲取總數 //需要增加AsExpandable(),否則查詢的是所有資料到記憶體,然後再排序 AsExpandable是linqkit.dll中的方法 return CommonSort(db.Set<T>().AsExpandable().Where(seleWhere), orderModelFiled).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList(); } } #endregion #region 原始sql操作 /// <summary> /// 執行操作 /// </summary> /// <param name="sql"></param> /// <param name="paras"></param> public void ExecuteSql(string sql, params object[] paras) { using (SysDb db = new SysDb(strConn)) { db.Database.ExecuteSqlCommand(sql, paras); } } /// <summary> /// 查詢列表 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="sql"></param> /// <param name="paras"></param> /// <returns></returns> public List<T> QueryList<T>(string sql, params object[] paras) where T : class { using (SysDb db = new SysDb(strConn)) { return db.Database.SqlQuery<T>(sql, paras).ToList(); } } /// <summary> /// 查詢單個 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="sql"></param> /// <param name="paras"></param> /// <returns></returns> public T QuerySingle<T>(string sql, params object[] paras) where T : class { using (SysDb<T> db = new SysDb<T>(strConn)) { return db.Database.SqlQuery<T>(sql, paras).FirstOrDefault(); } } /// <summary> /// 執行事務 /// </summary> /// <param name="lsSql"></param> /// <param name="lsParas"></param> public void ExecuteTransaction(List<String> lsSql, List<Object[]> lsParas) { using (SysDb db = new SysDb(strConn)) { using (var tran = db.Database.BeginTransaction()) { try { for (int i = 0; i < lsSql.Count; i++) { if (lsParas != null && lsParas.Count > 0) { db.Database.ExecuteSqlCommand(lsSql[i], lsParas[i]); } } foreach (String item in lsSql) { db.Database.ExecuteSqlCommand(item); } tran.Commit(); } catch (Exception ex) { tran.Rollback(); throw ex; } } } } #endregion #endregion #region 通用屬性 /// <summary> /// 獲取資料庫伺服器當前時間。 /// </summary> public DateTime ServerTime { get { using (SysDb db = new SysDb(strConn)) { String sql = "SELECT GETDATE()"; Object objServerTime = db.Database.SqlQuery<Object>(sql); return Convert.ToDateTime(objServerTime); } } } /// <summary> /// 獲取資料庫版本。 /// </summary> public String DatabaseVersion { get { using (SysDb db = new SysDb(strConn)) { try { String sql = "SELECT Version FROM Sys_Version"; Object objServerTime = db.Database.SqlQuery<Object>(sql); return Convert.ToString(objServerTime); } catch { } return String.Empty; } } } #endregion } public static class QueryableExtension { /// <summary> /// 擴充套件方法 支援 in 操作 /// </summary> /// <typeparam name="TEntity">需要擴充套件的物件型別</typeparam> /// <typeparam name="TValue">in 的值型別</typeparam> /// <param name="source">需要擴充套件的物件</param> /// <param name="valueSelector">值選擇器 例如c=>c.UserId</param> /// <param name="values">值集合</param> /// <returns></returns> public static IQueryable<TEntity> WhereIn<TEntity, TValue>(this IQueryable<TEntity> source, Expression<Func<TEntity, TValue>> valueSelector, IEnumerable<TValue> values) { if (null == valueSelector) { throw new ArgumentNullException("valueSelector"); } if (null == values) { throw new ArgumentNullException("values"); } ParameterExpression p = valueSelector.Parameters.Single(); if (!values.Any()) { return source; } var equals = values.Select(value => (Expression)Expression.Equal(valueSelector.Body, Expression.Constant(value, typeof(TValue)))); var body = equals.Aggregate<Expression>((accumulate, equal) => Expression.Or(accumulate, equal)); return source.Where(Expression.Lambda<Func<TEntity, bool>>(body, p)); } } public struct OrderModelField { public bool IsDESC { get; set; } public string PropertyName { get; set; } }
dbcontext類:
public class SysDb : DbContext { bool isNew = true;//是否是新的sql執行 string strMsg = "";//sql執行的相關資訊 string strConn = "";//資料庫連線字串 string UserName = "";//日誌使用者名稱稱 string AdditionalInfo = "";//日誌額外資訊 public SysDb(string connString) : // 資料庫連結字串 base(connString) { strConn = connString; Database.SetInitializer<SysDb>(null);//設定為空,防止自動檢查和生成 base.Database.Log = (info) => Debug.WriteLine(info); } public SysDb(string connString, string logUserName, string logAdditionalInfo) : // 資料庫連結字串 base(connString) { strConn = connString; Database.SetInitializer<SysDb>(null);//設定為空,防止自動檢查和生成 UserName = logUserName; AdditionalInfo = logAdditionalInfo; base.Database.Log = AddLogger; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { //去掉複數對映 modelBuilder.Conventions.Remove<PluralizingTableNameConvention>(); base.OnModelCreating(modelBuilder); } /// <summary> /// 新增日誌 /// </summary> /// <param name="info"></param> public void AddLogger(string info) { if (info != "\r\n" && (!info.Contains("Sys_EventLog"))) { string strTemp = info.ToUpper().Trim(); if (isNew) { //記錄增刪改 if (strTemp.StartsWith("INSERT") || strTemp.StartsWith("UPDATE") || strTemp.StartsWith("DELETE")) { strMsg = info; isNew = false; } } else { if (strTemp.StartsWith("CLOSED CONNECTION")) { //增加新日誌 using (SysDb db = new SysDb(strConn)) { try { //儲存日誌到資料庫或其他地方 } catch (Exception ex) { using (System.IO.StreamWriter sw = new System.IO.StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "//logError.txt")) { sw.Write(ex.Message); sw.Flush(); } } } //清空 strMsg = ""; isNew = true; } else { strMsg += info; } } } } } public class SysDb<T> : SysDb where T : class { public SysDb(string connString) : // 資料庫連結字串 base(connString) { Database.SetInitializer<SysDb<T>>(null);//設定為空,防止自動檢查和生成 } public SysDb(string connString, string logUserName, string logAdditionalInfo) : // 資料庫連結字串 base(connString,logUserName,logAdditionalInfo) { Database.SetInitializer<SysDb<T>>(null);//設定為空,防止自動檢查和生成 } public DbSet<T> Entities { get; set; } }
介面使用:(bll層忽略)
public class BusinessController : Controller { // // GET: /Jygl/Business/ BaseBLL basebll = new BaseBLL(WebHelper.Conn); public ActionResult GetXMList(int page,int rows) { int count = 0; //查詢條件 //Expression<Func<JY_XM, bool>> searchPredicate = PredicateBuilder.True<JY_XM>(); //searchPredicate = searchPredicate.And(c => c.UserName.Contains("")); Expression<Func<JY_XM, int>> keySelector = u => u.UID; string str = ExceptionHelper<JY_XM>.TryCatchPageQueryJson<int>(basebll.GetListPaged, page, rows, keySelector, false, out count); return Content(str); } [HttpPost] public ActionResult XMEdit(JY_XM jyxm) { basebll.Add(jyxm); return View(); } public ActionResult GetAllGCLB() { List<DICT_GCLB> lsGCLB = basebll.GetAll<DICT_GCLB>(); DICT_GCLB dicNew=new DICT_GCLB(); dicNew.GCLBText="-請選擇-"; dicNew.GCLBId=0; lsGCLB.Add(dicNew); return Content(WebHelper.Json(lsGCLB)); } public ActionResult GetAllArea() { List<DICT_Area> lsArea = basebll.GetAll<DICT_Area>(); DICT_Area dicNew=new DICT_Area(); dicNew.AreaText="-請選擇-"; dicNew.AreaId=0; lsArea.Add(dicNew); return Content(WebHelper.Json(lsArea)); } }
個人原創,歡迎轉載,尊重勞動成果,引用註明來源。