1. 程式人生 > >Entity Framework底層操作封裝V2版本(2)

Entity Framework底層操作封裝V2版本(2)

這個類是真正的資料庫操作類,上面的那個類只是呼叫了這個封裝類的方法進行的操作

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using System.Data.Entity;
using System.Data.Linq;
using System.Data.Objects;
using System.Reflection;
using System.Threading;
using System.Data;
using System.Data.Objects.DataClasses;
using JFrame.Utility;

namespace JFrame.AccessCommon
{
    public class DataCommon
    {
        static readonly string Connection = "name=EntitiesContainer";
        static readonly string ContainerName = "EntitiesContainer";
        ObjectContext entities;
        public DataCommon(string Connection, string ContainerName = "EntitiesContainer")
        {
            entities = new ObjectContext(Connection);
            entities.DefaultContainerName = ContainerName;
        }

        //POMonitorDBEntities entities = new ENTITY.POMonitorDBEntities(Connection);

        #region 根據SQL語句查詢資料
        public IEnumerable<T> ExecuteQuery<T>(string conn, string query, params object[] parms)
        {
            try
            {
                if (string.IsNullOrEmpty(conn))
                {
                    return entities.ExecuteStoreQuery<T>(query, parms);
                }
                else
                {
                    DataContext myDC = new DataContext(conn);
                    return myDC.ExecuteQuery<T>(query, parms);
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        public IEnumerable<T> ExecuteQuery<T>(string query)
        {
            return ExecuteQuery<T>(string.Empty, query, new object[] { });
        }
        #endregion

        #region 執行操作型別SQl語句
        /// <summary>
        /// 執行SQL命令
        /// </summary>
        /// <param name="sqlCommand"></param>
        /// <returns></returns>
        public int ExecuteSqlCommand(string sqlCommand, string connection = null)
        {
            if (string.IsNullOrEmpty(connection))
                return entities.ExecuteStoreCommand(sqlCommand); //ExecuteCommand(sqlCommand);
            else
            {
                ObjectContext entitiesNew = new ObjectContext(connection);
                return entitiesNew.ExecuteStoreCommand(sqlCommand);
            }
        }
        /// <summary>
        /// 執行SQL命令
        /// </summary>
        /// <param name="sqlCommand"></param>
        /// <returns></returns>
        public void ExecuteSqlCommand(string sqlCommand)
        {
            ExecuteSqlCommand(connection: string.Empty, sqlCommand: sqlCommand);
        }
        #endregion


        #region 私有方法
        private ObjectSet<T> GetTable<T>() where T : class
        {
            try
            {
                ObjectSet<T> customers = entities.CreateObjectSet<T>();
                return customers;
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }
        #endregion

        #region 統計指定條件的資料量
        /// <summary>
        /// 統計指定條件的資料量
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="query"></param>
        /// <returns></returns>
        public virtual int Count<T>(Expression<Func<T, bool>> query) where T : class
        {
            var table = GetTable<T>();
            return (from t in table
                    select t).Where(query).Count();
        }
        #endregion


        #region 獲取單個實體
        /// <summary>
        /// 獲取單個實體
        /// </summary>
        /// <typeparam name="T">泛型型別引數</typeparam>
        /// <param name="express">查詢條件</param>
        /// <returns></returns>
        public virtual T GetSingleEntity<T>(Expression<Func<T, bool>> query) where T : class
        {
            try
            {
                var table = GetTable<T>();
                return (from t in table
                        select t).Where(query).SingleOrDefault();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }




        #endregion

        ///<summary>
        ///獲取主鍵,此方式只適用於edmx資料表結構
        ///</summary>
        ///<param name="infos"></param>
        ///<returns></returns>
        private string getPrimaryKey(PropertyInfo[] infos)
        {
            string columnName = string.Empty;
            foreach (PropertyInfo propertyInfo in infos)
            {
                object[] customInfos = propertyInfo.GetCustomAttributes(typeof(EdmScalarPropertyAttribute), true);
                if (customInfos == null
               || customInfos.Length == 0)
                    return string.Empty;

                EdmScalarPropertyAttribute limit = customInfos.GetValue(0) as EdmScalarPropertyAttribute;
                if (limit.EntityKeyProperty)
                {
                    return columnName = propertyInfo.Name;
                }
            }
            return columnName;

        }

        //protected override string GetEntitySetName()
        //{
        //    return context.Products.EntitySet.Name;


        //}

        #region 更新實體
        public bool Update<T>(T entity, string PrimaryKey, object PrimaryKeyValue) where T : EntityObject
        {
            Type type = typeof(T);
            string strName = entities.Connection.ConnectionString.Replace("name=", "");
            EntityKey key = null;
            try
            {
                entity.EntityKey = entities.CreateEntityKey(type.Name, entity);
            }
            catch (Exception ex)
            {

            }

            try
            {
                key = entity.EntityKey;//new EntityKey("Entities." + type.Name, PrimaryKey, PrimaryKeyValue);
            }
            catch (Exception ex) 
            { }
            object propertyValue = null;
            T entityFromDB = (T)entities.GetObjectByKey(key);

            if (null == entityFromDB)
                return false;
            PropertyInfo[] properties1 = entityFromDB.GetType().GetProperties();
            foreach (PropertyInfo property in properties1)
            {
                propertyValue = null;
                if (null != property.GetSetMethod())
                {
                    PropertyInfo entityProperty =
                          entity.GetType().GetProperty(property.Name);
                    if (entityProperty.PropertyType.BaseType ==
                        Type.GetType("System.ValueType") ||
                        entityProperty.PropertyType ==
                        Type.GetType("System.String"))

                        propertyValue = entity.GetType().GetProperty(property.Name).GetValue(entity, null);
                    if (propertyValue == null)
                    {
                        Thread.Sleep(50);
                        propertyValue = entity.GetType().GetProperty(property.Name).GetValue(entity, null);
                    }
                    if (null != propertyValue)
                    {
                        try
                        {
                            string Name = property.Name;// "Reference";
                            if (Name.IndexOf("Reference") < 0)
                            {
                                property.SetValue(entityFromDB, propertyValue, null);
                            }
                        }
                        catch (Exception ex) { }
                    }
                }
            }


            entities.SaveChanges();
            return true;

        }

      
        #endregion


        #region 獲取相關的實體資訊
        /// <summary>
        /// 分頁_獲取指定頁的資料集合
        /// </summary>
        /// <typeparam name="T">泛型型別引數</typeparam>
        /// <param name="query">查詢條件</param>
        /// <param name="pageSize">每頁顯示數量</param>
        /// <param name="pageNum">當前頁號</param>
        /// <param name="pageTotal">總頁數</param>
        /// <param name="datasTotal">總資料量</param>
        /// <returns></returns>
        public virtual List<T> GetAllEntity<T>(Expression<Func<T, bool>> query, PagingInfo PageInfo, Func<T, object> orderByDesc) where T : class
        {
            var table = GetTable<T>();

            PageInfo.TotalRecord = (from t in table
                     select t).Where(query.Compile()).Count();
            PageInfo.TotalPage = PageInfo.TotalRecord / PageInfo.PageSize + 1;
            //string Sql=(table.Where(query.Compile()) as ObjectQuery).ToTraceString();
            return (from t in table
                    select t).Where(query.Compile()).OrderByDescending(orderByDesc).Skip(PageInfo.PageSize * (PageInfo.PageIndex - 1)).Take(PageInfo.PageSize).ToList();
        }
        /// <summary>
        /// 分頁_獲取指定頁的資料集合
        /// </summary>
        /// <typeparam name="T">泛型型別引數</typeparam>
        /// <param name="query">查詢條件</param>
        /// <param name="pageSize">每頁顯示數量</param>
        /// <param name="pageNum">當前頁號</param>
        /// <param name="pageTotal">總頁數</param>
        /// <param name="datasTotal">總資料量</param>
        /// <returns></returns>
        public virtual List<T> GetAllEntity<T>(Expression<Func<T, bool>> query, Func<T, object> orderByDesc, int pageSize, int pageNum, out int pageTotal, out int datasTotal) where T : class
        {
            var table = GetTable<T>();

            datasTotal = (from t in table
                          select t).Where(query).Count();

            pageTotal = (int)Math.Ceiling((double)datasTotal / pageSize);
            return (from t in table
                    select t).Where(query).OrderByDescending(orderByDesc).Skip(pageSize * (pageNum - 1)).Take(pageSize).ToList();
        }
        /// <summary>
        /// 獲取指定條件的實體集合

        /// </summary>
        /// <typeparam name="T">泛型型別引數</typeparam>
        /// <param name="query">查詢條件</param>
        /// <returns></returns>
        public virtual List<T> GetAllEntity<T>(Expression<Func<T, bool>> query) where T : class
        {
            var table = GetTable<T>();
            return (from t in table
                    select t).Where(query).ToList();
        }

        /// <summary>
        /// 獲取指定條件的實體集合

        /// </summary>
        /// <typeparam name="T">泛型型別引數</typeparam>
        /// <param name="query">查詢條件</param>      
        /// <param name="orderAsc"></param>       
        /// <returns></returns>
        public virtual List<T> GetAllEntity<T>(Expression<Func<T, bool>> query, bool isAsc, Func<T, object> order) where T : class
        {
            var table = GetTable<T>();
            if (isAsc)
                return (from t in table
                        select t).Where(query).OrderBy(order).ToList();
            return (from t in table
                    select t).Where(query).OrderByDescending(order).ToList();
        }

        public virtual List<T> GetAllEntity<T>() where T : class
        {
            var table = GetTable<T>();
            return (from t in table
                    select t).ToList();
        }
        #endregion


        #region 新增實體
        /// <summary>
        /// 新增單個實體
        /// </summary>
        /// <typeparam name="T">泛型型別引數</typeparam>
        /// <param name="entity">待插入的實體</param>
        /// <returns></returns>
        public virtual void InsertEntity<T>(T entity) where T : class
        {
            var table = GetTable<T>();
            table.AddObject(entity);
            entities.SaveChanges();
        }
        /// <summary>
        /// 批量新增實體
        /// </summary>
        /// <typeparam name="T">泛型型別引數</typeparam>
        /// <param name="entityList">待新增的實體集合</param>
        /// <returns></returns>
        public virtual void BatchInsertEntity<T>(List<T> entityList) where T : class
        {
            if (entityList.Count > 0)
            {
                var table = GetTable<T>();
                foreach (var item in entityList)
                {
                    table.AddObject(item);//DeleteAllOnSubmit(toDeletedColl);
                }
                entities.SaveChanges();
            }
        }
        #endregion

        #region 刪除實體
        /// <summary>
        /// 根據條件刪除指定實體
        /// </summary>
        /// <typeparam name="T">實體</typeparam>
        /// <param name="query">條件</param>
        /// <returns>bool</returns>
        public virtual void DeleteEntitys<T>(Expression<Func<T, bool>> query) where T : class
        {
            var table = GetTable<T>();
            var toDeletedColl = table.Where(query);
            if (toDeletedColl != null && toDeletedColl.Count() > 0)
            {
                foreach (var item in toDeletedColl)
                {
                    table.DeleteObject(item);//DeleteAllOnSubmit(toDeletedColl);
                }
                entities.SaveChanges();
            }
        }
        #endregion
    }
}

相關推薦

Entity Framework底層操作封裝V2版本2

這個類是真正的資料庫操作類,上面的那個類只是呼叫了這個封裝類的方法進行的操作 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System

Entity Framework底層操作封裝V2版本8

現在需要說說,需要注意的問題:在使用這個架子的時候一定需要注意的是:連線串一定要在配置檔案裡面定義好:庫1 庫2的連線串需要預先定義的。 <connectionStrings> <add name="EntitiesContainer" con

Entity Framework底層操作封裝V2版本5

這個框架到現在最大的變化馬上就要出現了,哪就是對快取的使用。因為系統經常要去讀取資料庫資料,但是大家知道,資料庫的處理能力是有限的,所以對於一些資料量不大,但是又 需要經常去讀取的功能來說,更好的方法就是使用快取。 上面4的方法是不適用快取的 using System;

Entity Framework底層操作封裝V2版本3

現在是附加的,組合查詢需要的擴充套件類。大家知道lanmda表示式的組合條件比較麻煩,所以就加了一樣一個類,方便進行組合查詢: using System; using System.Collections.Generic; using System.Linq; using

Entity Framework底層操作封裝V2版本3

如今是附加的。組合查詢須要的擴充套件類。 大家知道lanmda表示式的組合條件比較麻煩。所以就加了一樣一個類,方便進行組合查詢: using System; using System.Collections.Generic; using System.Linq; using Sy

Entity Framework底層操作封裝(1)

最近做移動的專案,要求底層資料庫是Oracle,但是因為本機是Sqlserver的環境。想了下,於是使用Entity Framework 進行開發,在開發完成以後切換到Oracle環境。想了下,就決定把以前封裝的Linq的底層操作類進行了修改,形成EF的底層操作類。這樣在自

二次封裝函數2

rgs using 返回 技術分享 PE family his RR class 題目描述 實現函數 partialUsingArguments,調用之後滿足如下條件: 1、返回一個函數 result 2、調用 result 之後,返回的結果與調用函數 fn 的結果一致

手把手教你做一個新浪部落格釋出軟體JAVA版本2--環境準備

          前言:很多人用新浪部落格引流,但是以前可以用api釋出,但是現在已經行不通了,市面上也有諸如新浪部落格批量釋出軟體啦,新浪部落格批量發帖啦,新浪部落格釋出軟體啊等等的各種工具,但是小心中槍,一不小心就封號處理了,所以得不償失,於是

深入理解Mysql索引的底層資料結構 B+ Tree 2

  sql查詢 explain的詳細用法 操作時間:尋道時間+旋轉時間 引入索引:採用二叉樹結構 把第二列做為索引生成二叉樹結構,此時查詢89 只做了兩次io操作 但是mysql 為什麼不用二叉樹作為底層索引結構? 紅黑樹 hash where col1 > 6

Python呼叫採用Boost Python封裝的c++2

     上次我寫了利用Python提供的API封裝c函式,並呼叫。但是由於利用API的方式過於原始,對於類或者結構極度麻煩。因此,我選擇了Boost的Python的來封裝類,類似的工具還有SWIG等,

Kinect V2開發2從Kinect獲取資料

在Kinect for windows SDK2.0中,Kinect有多種型別的資料來源,每個型別的資料都有三個類與之對應:Source,Reader和Frame。要讀取骨架,就有IBodyFrameSource, IBodyFrameReader, IBody

Entity Framework Core 入門2

安裝 EF Core 將 EF Core 新增到不同平臺和常用 IDE 中的應用程式的所需步驟彙總。 分步入門教程 無需具備 Entity Framework Core 或任何特定 IDE 的原有知識,即可學習這些入門教程。 這些教程將逐步介紹如何建立用於查詢和儲存資料庫中資料的簡單應用程式。

git操作總結2:回退和前進到某一個版本

1.檢視日誌: git log 簡化命令 git log --pretty=oneline 2.回退到上一個版本  git reset HEAD^     註釋:         用HEAD表示當前版本,上一個版

Robot Framework - 入門與操作2

04- 建立測試庫--基礎概念 Robot Framework 實際的測試能力是由測試庫提供的。 ***** 支援的程式語言 Robot Framework 自身是用 Python 編寫的,能使用 Python 擴充套件測試庫。 如果在 Jython 執行Robot Frame

高階查詢元件dynamicCondition升級為v2.0.0版本

新版本特性: 1.新增ops和allowDel屬性。 <ul id="dynamicCondition" style="display:none;"> <li field="DynamicCondition.id" title="id" edit="text" l

高階查詢元件dynamicCondition升級為v2.0.0版本

效果預覽: 1.省份和城市可以實現聯動效果。 2.可以自定義查詢條件編輯器。如下拉樹,單選按鈕組。 新版本特性: 1.新增ops和allowDel屬性 2.支援擴充套件編輯器。可以實現下拉框級聯,下拉樹,單選組等ui控制元件。 3.新增輔助介面:instance.getRowDiv

封裝位元組流byte[]操作類 c#

在網路通訊中,資料在網路傳輸的格式必須以位元組流的形式進行,因此需要我們對位元組流進行寫入和讀出的操作,下面將會封裝兩個類,用來將各種型別的資料寫入位元組流,和從位元組流中讀取各種型別的資料。如下讀取類:NetBufferReaderusing System; using S

faster_rcnn c++版本的 caffe 封裝,動態庫2

在上一篇文章中,我們是將對caffe的呼叫隔離了出來,可以說相當於原來caffe原始碼下的tools中cpp檔案使用相同,然後自己寫了個CMakeLists.txt進行編譯。這裡是進一步將程式碼進行分離,封裝成libfaster_rcnn.so檔案進行使用。對於部分介面,我可能做了一些改動。 目錄結構 ├

Entity Framework】MVC基架不支援Entity Framework 6或更高版本

MVC基架不支援Entity Framework 6或更高版本。有關詳細資訊,請訪問http://go.microsoft.com/fwlink/?LinkId=276833 在【管理Nuget程式包】->【已安裝的包】->【全部】->【Entity F

easyui.utils.js 自己封裝的 使用easyui過程中方便操作和取值

注意:該easyui.utils.js  會在我自己使用過程中不斷完善,大家一起進步。 在js上新增 以下 (function($){   function  其他方法。 })(jQuery); 的目的是為了防止該js檔案中的function與瀏覽器本身的一些functi