1. 程式人生 > >c#EntityFormwork框架工具類

c#EntityFormwork框架工具類

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Linq.Expressions;

namespace CompanyWeb.Content.Tools
{
    /// <summary>
    /// Entity FrameWork幫助類(提供各種對資料的操作方法)
    /// </summary>
    /// <typeparam name="TDbContext"></typeparam>
    public class EFTools<TDbContext> where TDbContext : DbContext, new()
    {

        /// <summary>
        /// 獲取所有的實體  zhaolin 
        /// </summary>
        /// <typeparam name="T"> 泛型實體型別  在呼叫前必須制定 且只能為引用型別</typeparam>
        /// <returns>結果集</returns>
        public List<T> GetAllEntity<T>() where T : class
        {
            try
            {
                using (TDbContext db = new TDbContext())
                {
                    return db.Set<T>().ToList();

                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return new List<T>();
            }

        }

        /// <summary>
        /// 獲取單個實體(條件的最後一條)
        /// </summary>
        /// <typeparam name="T">泛型實體型別  在呼叫前必須制定 且只能為引用型別</typeparam>
        /// <param name="whereProc">過濾的表示式</param>
        /// <returns>實體</returns>
        public T GetSingleEntityLast<T, Tkey>(Expression<Func<T, bool>> whereProc, Expression<Func<T, Tkey>> orderProc, string desc) where T : class
        {
            try
            {

                using (TDbContext ef = new TDbContext())
                {

                    if (desc == "desc")
                    {
                        return ef.Set<T>().Where(whereProc).OrderByDescending(orderProc).FirstOrDefault();
                    }

                    return ef.Set<T>().Where(whereProc).OrderBy(orderProc).FirstOrDefault();

                    // return ef.Set<T>().FirstOrDefault(whereProc);

                }


            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return null;
            }
        }


        /// <summary>
        /// 獲取所有的實體可排序  
        /// </summary>
        /// <typeparam name="T">泛型實體型別  在呼叫前必須制定 且只能為引用型別</typeparam>
        /// <param name="orderProc"> 排序表示式</param>
        /// <param name="orderByType">排序的型別 預設是升序,降序(desc)</param>
        /// <returns>結果集</returns>
        public List<T> GetAllEntityByOrder<T, TKey>(Expression<Func<T, TKey>> orderProc, string orderByType) where T : class
        {
            try
            {
                using (TDbContext db = new TDbContext())
                {

                    if (orderByType == "desc")
                    {
                        return db.Set<T>().OrderByDescending(orderProc).ToList();
                    }

                    return db.Set<T>().OrderBy(orderProc).ToList();
                }
            }
            catch (Exception)
            {
                return new List<T>();
            }

        }

        /// <summary>
        /// 獲取所有的實體可排序
        /// </summary>
        /// <typeparam name="T">泛型實體型別  在呼叫前必須制定 且只能為引用型別</typeparam>
        /// <param name="whereProc"> 過濾的表示式</param>
        /// <returns>結果集</returns>
        public List<T> GetAllEntityByWhere<T>(Expression<Func<T, bool>> whereProc) where T : class
        {
            try
            {
                using (TDbContext db = new TDbContext())
                {

                    return db.Set<T>().Where(whereProc).ToList();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return new List<T>();
            }

        }


        /// <summary>
        /// 獲取所有的實體可排序  
        /// </summary>
        /// <typeparam name="T">泛型實體型別  在呼叫前必須制定 且只能為引用型別</typeparam>
        /// <typeparam name="TKey">成員屬性的型別</typeparam>
        /// /// <param name="whereProc">過濾的表示式</param>
        /// <param name="orderProc">排序的表示式</param>
        /// <param name="orderByType">排序的型別</param>
        /// <returns>結果集</returns>
        public List<T> GetAllEntityOrderAndWhere<T, TKey>(Expression<Func<T, bool>> whereProc, Expression<Func<T, TKey>> orderProc, string orderByType) where T : class
        {
            try
            {
                using (TDbContext db = new TDbContext())
                {

                    if (orderByType == "desc")
                    {
                        return db.Set<T>().Where(whereProc).OrderByDescending(orderProc).ToList();
                    }


                    return db.Set<T>().Where(whereProc).OrderBy(orderProc).ToList();
                }
            }
            catch (Exception)
            {
                return new List<T>();
            }

        }



        /// <summary>
        /// 獲取某一個實體型別的所有資料並排序
        /// </summary>
        /// <typeparam name="TEntity">待查詢的實體的型別</typeparam>
        /// <typeparam name="TKey">排序的條件的屬性的數值型別</typeparam>
        /// <param name="OrderByProc">排序的lambda表示式</param>
        /// <param name="IsDesc">false 順序 true 逆序</param>
        /// <returns>失敗或者沒有資料 返回 空集合 否則返回  查詢的到結果集</returns>
        public List<TEntity> GetAllEntitysAndOrderBy<TEntity, TKey>(Expression<Func<TEntity, TKey>> OrderByProc, bool IsDesc) where TEntity : class
        {
            try
            {
                using (TDbContext db = new TDbContext())
                {

                    if (IsDesc)
                    {
                        return db.Set<TEntity>().OrderByDescending(OrderByProc).ToList();
                    }
                    return db.Set<TEntity>().OrderBy(OrderByProc).ToList();
                }
            }
            catch (Exception exp)
            {
                Console.WriteLine(exp.Message);
                return new List<TEntity>();
            }
        }

        /// <summary>
        /// 獲取單個實體
        /// </summary>
        /// <typeparam name="T">泛型實體型別  在呼叫前必須制定 且只能為引用型別</typeparam>
        /// <param name="whereProc">過濾的表示式</param>
        /// <returns>實體</returns>
        public T GetSingleEntity<T>(Expression<Func<T, bool>> whereProc) where T : class
        {
            try
            {

                using (TDbContext ef = new TDbContext())
                {

                    return ef.Set<T>().Where(whereProc).FirstOrDefault();

                    // return ef.Set<T>().FirstOrDefault(whereProc);

                }


            }
            catch (Exception)
            {

                return null;
            }


        }


        /// <summary>
        /// 按條件查詢排序後獲取最後一個
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <typeparam name="TKey"></typeparam>
        /// <param name="WhereProc"></param>
        /// <param name="OrderByProcDesc"></param>
        /// <returns></returns>
        public TEntity GetLastEntity<TEntity, TKey>(Expression<Func<TEntity, bool>> WhereProc, Expression<Func<TEntity, TKey>> OrderByProcDesc) where TEntity : class
        {
            try
            {
                using (TDbContext db = new TDbContext())
                {
                    return db.Set<TEntity>().Where(WhereProc).OrderByDescending(OrderByProcDesc).FirstOrDefault();
                }
            }
            catch (Exception exp)
            {
                Console.WriteLine(exp.Message);
                return null;

            }
        }


        /// <summary>
        /// 獲取分頁的實體
        /// </summary>
        /// <typeparam name="T">泛型實體型別  在呼叫前必須制定 且只能為引用型別</typeparam>
        /// <typeparam name="TKey">成員屬性的型別</typeparam>
        /// <param name="pageIndex">當前的頁碼</param>
        /// <param name="pageCount">每頁顯示的行數</param>
        /// <param name="orderProc">排序的表示式</param>
        /// <param name="orderByType">排序的型別</param>
        /// <returns></returns>
        public List<T> GetPageEntityByOrder<T, TKey>(int pageIndex, int pageCount, Expression<Func<T, TKey>> orderProc, string orderByType) where T : class
        {
            try
            {
                using (TDbContext ef = new TDbContext())
                {

                    if (orderByType == "desc")
                    {
                        return ef.Set<T>().OrderByDescending(orderProc).Skip((pageIndex - 1) * pageCount).Take(pageCount).ToList();
                    }

                    return ef.Set<T>().OrderBy(orderProc).Skip((pageIndex - 1) * pageCount).Take(pageCount).ToList();


                }


            }
            catch (Exception)
            {

                return new List<T>();
            }

        }


        /// <summary>
        /// 獲取分頁的實體
        /// </summary>
        /// <typeparam name="T">泛型實體型別  在呼叫前必須制定 且只能為引用型別</typeparam>
        /// <typeparam name="TKey">成員屬性的型別</typeparam>
        /// <param name="pageIndex">當前的頁碼</param>
        /// <param name="pageCount">每頁顯示的行數</param>
        /// <param name="whereProc">過濾的表示式</param>
        /// <param name="orderProc">排序的表示式</param>
        /// <param name="orderByType">排序的型別</param>
        /// <returns></returns>
        public List<T> GetPageEntityByOrderAndWhere<T, TKey>(int pageIndex, int pageCount, Expression<Func<T, bool>> whereProc, Expression<Func<T, TKey>> orderProc, string orderByType) where T : class
        {
            try
            {
                using (TDbContext ef = new TDbContext())
                {

                    if (orderByType == "desc")
                    {
                        return ef.Set<T>().OrderByDescending(orderProc).Where(whereProc).Skip((pageIndex - 1) * pageCount).Take(pageCount).ToList();
                    }

                    return ef.Set<T>().OrderBy(orderProc).Where(whereProc).Skip((pageIndex - 1) * pageCount).Take(pageCount).ToList();





                }


            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return new List<T>();
            }

        }


        /// <summary>
        ///獲取 按條件過濾排序分組 資料
        /// </summary>
        /// <typeparam name="T">泛型實體型別  在呼叫前必須制定 且只能為引用型別</typeparam>
        /// <typeparam name="TKey">成員屬性的型別</typeparam>
        /// <typeparam name="TKey2">成員屬性的型別</typeparam>
        /// <param name="whereProc">過濾的表示式</param>
        /// <param name="orderProc">排序的表示式</param>
        /// <param name="orderByType">排序的型別</param>
        /// <param name="groupProc">分組的表示式</param>
        /// <returns></returns>
        public List<T> GetEntityAndGroup<T, TKey, TKey2>(Expression<Func<T, bool>> whereProc, Expression<Func<T, TKey>> orderProc, string orderByType, Expression<Func<T, TKey2>> groupProc) where T : class
        {


            try
            {
                List<T> list = new List<T>();

                using (TDbContext ef = new TDbContext())
                {


                    if (orderByType == "desc")
                    {
                        var Groups = ef.Set<T>().Where(whereProc).OrderByDescending(orderProc).GroupBy(groupProc).ToList();

                        Groups.ForEach(G => { list.AddRange(G); });
                    }
                    else
                    {
                        var Groups = ef.Set<T>().Where(whereProc).OrderBy(orderProc).GroupBy(groupProc).ToList();

                        Groups.ForEach(G => { list.AddRange(G); });
                    }
                    return list;

                }


            }
            catch (Exception)
            {

                return new List<T>();
            }


        }



        /// <summary>
        /// 分頁
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="pageIndex">當前是第幾頁</param>
        /// <param name="pageCount">每一頁的行數</param>
        /// <returns></returns>
        public List<T> GetEntityByPage<T, Tkey>(int pageIndex, int pageCount, Expression<Func<T, Tkey>> orderExp, Expression<Func<T, bool>> whereExp) where T : class
        {

            try
            {
                TDbContext db = new TDbContext();
                if (whereExp == null)
                {
                    return db.Set<T>().OrderBy(orderExp).Skip((pageIndex - 1) * pageCount).Take(pageCount).ToList();
                }
                else
                {
                    return db.Set<T>().OrderBy(orderExp).Where(whereExp).Skip((pageIndex - 1) * pageCount).Take(pageCount).ToList();
                }

            }
            catch (Exception)
            {

                return null;
            }
        }




        /// <summary>
        /// 獲取總條數
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="whereExp"></param>
        /// <returns></returns>
        public int GetAllCount<T>(Expression<Func<T, bool>> whereExp) where T : class
        {
            TDbContext db = new TDbContext();
            if (whereExp == null)
            {
                return db.Set<T>().ToList().Count;
            }
            else
            {
                return db.Set<T>().Where(whereExp).ToList().Count;
            }


        }




        /// <summary>
        /// 根據條件刪除
        /// </summary>
        /// <typeparam name="T">泛型實體型別  在呼叫前必須制定 且只能為引用型別</typeparam>
        /// <param name="whereProc">刪除的條件</param>
        /// <returns>結果</returns>
        public bool DeleteEntityByWhere<T>(Expression<Func<T, bool>> whereProc) where T : class
        {
            try
            {
                using (TDbContext ef = new TDbContext())
                {


                    List<T> list = ef.Set<T>().Where(whereProc).ToList();

                    if (list == null || list.Count == 0)
                    {
                        return true;
                    }

                    list.ForEach(R =>
                    {

                        ef.Set<T>().Remove(R);

                    });



                    return ef.SaveChanges() > 0;

                }


            }
            catch (Exception)
            {

                return false;
            }


        }



        /// <summary>
        /// 刪除單個實體
        /// </summary>
        /// <typeparam name="T">泛型實體型別  在呼叫前必須制定 且只能為引用型別</typeparam>
        /// <param name="t">待刪除的實體</param>
        /// <returns>結果</returns>
        public bool DeleteEntity<T>(T t) where T : class
        {
            try
            {

                using (TDbContext ef = new TDbContext())
                {
                    ef.Set<T>().Attach(t);
                    ef.Set<T>().Remove(t);

                    //var  entity =    ef.Entry<T>(t);
                    //entity.State = System.Data.EntityState.Deleted;


                    return ef.SaveChanges() > 0;



                }

            }
            catch (Exception)
            {

                return false;
            }


        }


        /// <summary>
        /// 刪除多個
        /// </summary>
        /// <typeparam name="T">泛型實體型別  在呼叫前必須制定 且只能為引用型別</typeparam>
        /// <param name="tlist">待刪除的集合</param>
        /// <returns>結果</returns>

        public bool DelEntity<T>(List<T> tlist) where T : class
        {
            try
            {
                using (TDbContext ef = new TDbContext())
                {
                    if (tlist.Count == 0)
                    {
                        return true;
                    }

                    foreach (var item in tlist)
                    {
                        ef.Set<T>().Attach(item);

                        ef.Set<T>().Remove(item);
                    }

                    return ef.SaveChanges() > 0;

                }

            }


            catch (Exception)
            {

                return false;
            }
        }

        /// <summary>
        /// 根據條件刪除許可權
        /// </summary>
        /// <typeparam name="T">泛型實體型別  在呼叫前必須制定 且只能為引用型別</typeparam>
        /// <param name="whereProc">刪除的條件</param>
        /// <returns>結果</returns>
        public bool DeleteClass<T>(Expression<Func<T, bool>> whereProc) where T : class
        {
            try
            {
                using (TDbContext ef = new TDbContext())
                {


                    List<T> list = ef.Set<T>().Where(whereProc).ToList();

                    if (list == null || list.Count == 0)
                    {
                        return true;
                    }

                    list.ForEach(R =>
                    {

                        ef.Set<T>().Remove(R);

                    });



                    return ef.SaveChanges() > 0;

                }


            }
            catch (Exception)
            {

                return false;
            }


        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <returns></returns>
        public bool UpdateEntity<T>(T t) where T : class
        {
            try
            {
                using (TDbContext ef = new TDbContext())
                {

                    if (ef.Entry<T>(t).State == System.Data.Entity.EntityState.Detached)
                    {
                        ef.Set<T>().Attach(t);
                        ef.Entry<T>(t).State = System.Data.Entity.EntityState.Modified;
                    }
                    return ef.SaveChanges() > 0;
                }

            }
            catch (Exception ex)
            {

                string error = ex.Message;
                return false;
            }

        }

        /// <summary>
        /// 新增實體
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <returns></returns>
        public bool AddEntity<T>(T t) where T : class
        {

            try
            {
                using (TDbContext ef = new TDbContext())
                {


                    ef.Set<T>().Add(t);

                    return ef.SaveChanges() > 0;

                }

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return false;
            }


        }
        /// <summary>
        /// 根據sql查詢資料 (可以使自定義實體)
        /// </summary>
        /// <typeparam name="TModel">實體型別</typeparam>
        /// <param name="sql">sql語句</param>
        /// <returns>失敗或者沒有資料 返回 空集合 否則返回  查詢的到結果集</returns>
        public List<TModel> GetDataBySql<TModel>(string sql) where TModel : class
        {
            try
            {
                using (TDbContext db = new TDbContext())
                {

                    return db.Database.SqlQuery<TModel>(sql).ToList();
                }
            }
            catch (Exception exp)
            {
                Console.WriteLine(exp.Message);
                return new List<TModel>();
            }
        }





        /// <summary>
        /// 執行sql  增加   刪除   修改
        /// </summary>
        /// <param name="sql">增加   刪除   修改  sql</param>
        /// <returns>true  成功  false  失敗</returns>
        public bool ExcuteSql(string sql)
        {
            try
            {
                using (TDbContext db = new TDbContext())
                {

                    return db.Database.ExecuteSqlCommand(sql) > 0;

                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return false;
            }
        }
        /// <summary>
        /// 新增一組資料
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="tlist"></param>
        /// <returns></returns>
        public bool AddClass<T>(List<T> tlist) where T : class
        {
            try
            {
                using (TDbContext ef = new TDbContext())
                {
                    if (tlist.Count == 0)
                    {
                        return true;
                    }

                    foreach (var item in tlist)
                    {
                        ef.Set<T>().Add(item);
                    }

                    return ef.SaveChanges() > 0;
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return false;
            }
        }

        /// <summary>
        /// 獲取分頁資料(不需要條件)
        /// </summary>
        /// <typeparam name="T">實體型別</typeparam>
        /// <typeparam name="TN">實體的成員屬性的型別</typeparam>
        /// <param name="pageIndex">當前請求的頁面</param>
        /// <param name="pageCount">每頁的行數</param>
        /// <param name="orderByProc">排序的表示式</param>
        /// <returns></returns>
        public List<T> GetPageEntity<T, TN>(int pageIndex, int pageCount, Expression<Func<T, TN>> orderByProc, Expression<Func<T, bool>> whereExp) where T : class
        {
            try
            {

                using (TDbContext ef = new TDbContext())
                {
                    if (whereExp == null)
                    {
                        return ef.Set<T>().OrderBy(orderByProc).Skip((pageIndex - 1) * pageCount).Take(pageCount).ToList();
                    }

                    return ef.Set<T>().OrderBy(orderByProc).Skip((pageIndex - 1) * pageCount).Take(pageCount).Where(whereExp).ToList();
                }



            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return null;
            }
        }
    }
}

記錄自己用過的東西   以免遺忘!