Entity Framework底层操作封装V2版本(2)

这个类是真正的数据库操作类,上面的那个类只是调用了这个封装类的方法进行的操作

[csharp] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Linq.Expressions;  
  6. using System.Data.Entity;  
  7. using System.Data.Linq;  
  8. using System.Data.Objects;  
  9. using System.Reflection;  
  10. using System.Threading;  
  11. using System.Data;  
  12. using System.Data.Objects.DataClasses;  
  13. using JFrame.Utility;  
  14.   
  15. namespace JFrame.AccessCommon  
  16. {  
  17.     public class DataCommon  
  18.     {  
  19.         static readonly string Connection = "name=EntitiesContainer";  
  20.         static readonly string ContainerName = "EntitiesContainer";  
  21.         ObjectContext entities;  
  22.         public DataCommon(string Connection, string ContainerName = "EntitiesContainer")  
  23.         {  
  24.             entities = new ObjectContext(Connection);  
  25.             entities.DefaultContainerName = ContainerName;  
  26.         }  
  27.   
  28.         //POMonitorDBEntities entities = new ENTITY.POMonitorDBEntities(Connection);  
  29.  
  30.         #region 根据SQL语句查询数据  
  31.         public IEnumerable<T> ExecuteQuery<T>(string conn, string query, params object[] parms)  
  32.         {  
  33.             try  
  34.             {  
  35.                 if (string.IsNullOrEmpty(conn))  
  36.                 {  
  37.                     return entities.ExecuteStoreQuery<T>(query, parms);  
  38.                 }  
  39.                 else  
  40.                 {  
  41.                     DataContext myDC = new DataContext(conn);  
  42.                     return myDC.ExecuteQuery<T>(query, parms);  
  43.                 }  
  44.             }  
  45.             catch (Exception ex)  
  46.             {  
  47.                 throw new Exception(ex.Message);  
  48.             }  
  49.         }  
  50.         public IEnumerable<T> ExecuteQuery<T>(string query)  
  51.         {  
  52.             return ExecuteQuery<T>(string.Empty, query, new object[] { });  
  53.         }  
  54.         #endregion  
  55.  
  56.         #region 执行操作类型SQl语句  
  57.         /// <summary>  
  58.         /// 执行SQL命令  
  59.         /// </summary>  
  60.         /// <param name="sqlCommand"></param>  
  61.         /// <returns></returns>  
  62.         public int ExecuteSqlCommand(string sqlCommand, string connection = null)  
  63.         {  
  64.             if (string.IsNullOrEmpty(connection))  
  65.                 return entities.ExecuteStoreCommand(sqlCommand); //ExecuteCommand(sqlCommand);  
  66.             else  
  67.             {  
  68.                 ObjectContext entitiesNew = new ObjectContext(connection);  
  69.                 return entitiesNew.ExecuteStoreCommand(sqlCommand);  
  70.             }  
  71.         }  
  72.         /// <summary>  
  73.         /// 执行SQL命令  
  74.         /// </summary>  
  75.         /// <param name="sqlCommand"></param>  
  76.         /// <returns></returns>  
  77.         public void ExecuteSqlCommand(string sqlCommand)  
  78.         {  
  79.             ExecuteSqlCommand(connection: string.Empty, sqlCommand: sqlCommand);  
  80.         }  
  81.         #endregion  
  82.  
  83.  
  84.         #region 私有方法  
  85.         private ObjectSet<T> GetTable<T>() where T : class  
  86.         {  
  87.             try  
  88.             {  
  89.                 ObjectSet<T> customers = entities.CreateObjectSet<T>();  
  90.                 return customers;  
  91.             }  
  92.             catch (Exception ex)  
  93.             {  
  94.                 throw ex;  
  95.             }  
  96.   
  97.         }  
  98.         #endregion  
  99.  
  100.         #region 统计指定条件的数据量  
  101.         /// <summary>  
  102.         /// 统计指定条件的数据量  
  103.         /// </summary>  
  104.         /// <typeparam name="T"></typeparam>  
  105.         /// <param name="query"></param>  
  106.         /// <returns></returns>  
  107.         public virtual int Count<T>(Expression<Func<T, bool>> query) where T : class  
  108.         {  
  109.             var table = GetTable<T>();  
  110.             return (from t in table  
  111.                     select t).Where(query).Count();  
  112.         }  
  113.         #endregion  
  114.  
  115.  
  116.         #region 获取单个实体  
  117.         /// <summary>  
  118.         /// 获取单个实体  
  119.         /// </summary>  
  120.         /// <typeparam name="T">泛型类型参数</typeparam>  
  121.         /// <param name="express">查询条件</param>  
  122.         /// <returns></returns>  
  123.         public virtual T GetSingleEntity<T>(Expression<Func<T, bool>> query) where T : class  
  124.         {  
  125.             try  
  126.             {  
  127.                 var table = GetTable<T>();  
  128.                 return (from t in table  
  129.                         select t).Where(query).SingleOrDefault();  
  130.             }  
  131.             catch (Exception ex)  
  132.             {  
  133.                 throw ex;  
  134.             }  
  135.         }  
  136.  
  137.  
  138.  
  139.  
  140.         #endregion  
  141.   
  142.         ///<summary>  
  143.         ///获取主键,此方式只适用于edmx数据表结构  
  144.         ///</summary>  
  145.         ///<param name="infos"></param>  
  146.         ///<returns></returns>  
  147.         private string getPrimaryKey(PropertyInfo[] infos)  
  148.         {  
  149.             string columnName = string.Empty;  
  150.             foreach (PropertyInfo propertyInfo in infos)  
  151.             {  
  152.                 object[] customInfos = propertyInfo.GetCustomAttributes(typeof(EdmScalarPropertyAttribute), true);  
  153.                 if (customInfos == null  
  154.                || customInfos.Length == 0)  
  155.                     return string.Empty;  
  156.   
  157.                 EdmScalarPropertyAttribute limit = customInfos.GetValue(0) as EdmScalarPropertyAttribute;  
  158.                 if (limit.EntityKeyProperty)  
  159.                 {  
  160.                     return columnName = propertyInfo.Name;  
  161.                 }  
  162.             }  
  163.             return columnName;  
  164.   
  165.         }  
  166.   
  167.         //protected override string GetEntitySetName()  
  168.         //{  
  169.         //    return context.Products.EntitySet.Name;  
  170.   
  171.   
  172.         //}  
  173.  
  174.         #region 更新实体  
  175.         public bool Update<T>(T entity, string PrimaryKey, object PrimaryKeyValue) where T : EntityObject  
  176.         {  
  177.             Type type = typeof(T);  
  178.             string strName = entities.Connection.ConnectionString.Replace("name=", "");  
  179.             EntityKey key = null;  
  180.             try  
  181.             {  
  182.                 entity.EntityKey = entities.CreateEntityKey(type.Name, entity);  
  183.             }  
  184.             catch (Exception ex)  
  185.             {  
  186.   
  187.             }  
  188.   
  189.             try  
  190.             {  
  191.                 key = entity.EntityKey;//new EntityKey("Entities." + type.Name, PrimaryKey, PrimaryKeyValue);  
  192.             }  
  193.             catch (Exception ex)   
  194.             { }  
  195.             object propertyValue = null;  
  196.             T entityFromDB = (T)entities.GetObjectByKey(key);  
  197.   
  198.             if (null == entityFromDB)  
  199.                 return false;  
  200.             PropertyInfo[] properties1 = entityFromDB.GetType().GetProperties();  
  201.             foreach (PropertyInfo property in properties1)  
  202.             {  
  203.                 propertyValue = null;  
  204.                 if (null != property.GetSetMethod())  
  205.                 {  
  206.                     PropertyInfo entityProperty =  
  207.                           entity.GetType().GetProperty(property.Name);  
  208.                     if (entityProperty.PropertyType.BaseType ==  
  209.                         Type.GetType("System.ValueType") ||  
  210.                         entityProperty.PropertyType ==  
  211.                         Type.GetType("System.String"))  
  212.   
  213.                         propertyValue = entity.GetType().GetProperty(property.Name).GetValue(entity, null);  
  214.                     if (propertyValue == null)  
  215.                     {  
  216.                         Thread.Sleep(50);  
  217.                         propertyValue = entity.GetType().GetProperty(property.Name).GetValue(entity, null);  
  218.                     }  
  219.                     if (null != propertyValue)  
  220.                     {  
  221.                         try  
  222.                         {  
  223.                             string Name = property.Name;// "Reference";  
  224.                             if (Name.IndexOf("Reference") < 0)  
  225.                             {  
  226.                                 property.SetValue(entityFromDB, propertyValue, null);  
  227.                             }  
  228.                         }  
  229.                         catch (Exception ex) { }  
  230.                     }  
  231.                 }  
  232.             }  
  233.   
  234.   
  235.             entities.SaveChanges();  
  236.             return true;  
  237.   
  238.         }  
  239.  
  240.        
  241.         #endregion  
  242.  
  243.  
  244.         #region 获取相关的实体信息  
  245.         /// <summary>  
  246.         /// 分页_获取指定页的数据集合  
  247.         /// </summary>  
  248.         /// <typeparam name="T">泛型类型参数</typeparam>  
  249.         /// <param name="query">查询条件</param>  
  250.         /// <param name="pageSize">每页显示数量</param>  
  251.         /// <param name="pageNum">当前页号</param>  
  252.         /// <param name="pageTotal">总页数</param>  
  253.         /// <param name="datasTotal">总数据量</param>  
  254.         /// <returns></returns>  
  255.         public virtual List<T> GetAllEntity<T>(Expression<Func<T, bool>> query, PagingInfo PageInfo, Func<T, object> orderByDesc) where T : class  
  256.         {  
  257.             var table = GetTable<T>();  
  258.   
  259.             PageInfo.TotalRecord = (from t in table  
  260.                      select t).Where(query.Compile()).Count();  
  261.             PageInfo.TotalPage = PageInfo.TotalRecord / PageInfo.PageSize + 1;  
  262.             //string Sql=(table.Where(query.Compile()) as ObjectQuery).ToTraceString();  
  263.             return (from t in table  
  264.                     select t).Where(query.Compile()).OrderByDescending(orderByDesc).Skip(PageInfo.PageSize * (PageInfo.PageIndex - 1)).Take(PageInfo.PageSize).ToList();  
  265.         }  
  266.         /// <summary>  
  267.         /// 分页_获取指定页的数据集合  
  268.         /// </summary>  
  269.         /// <typeparam name="T">泛型类型参数</typeparam>  
  270.         /// <param name="query">查询条件</param>  
  271.         /// <param name="pageSize">每页显示数量</param>  
  272.         /// <param name="pageNum">当前页号</param>  
  273.         /// <param name="pageTotal">总页数</param>  
  274.         /// <param name="datasTotal">总数据量</param>  
  275.         /// <returns></returns>  
  276.         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  
  277.         {  
  278.             var table = GetTable<T>();  
  279.   
  280.             datasTotal = (from t in table  
  281.                           select t).Where(query).Count();  
  282.   
  283.             pageTotal = (int)Math.Ceiling((double)datasTotal / pageSize);  
  284.             return (from t in table  
  285.                     select t).Where(query).OrderByDescending(orderByDesc).Skip(pageSize * (pageNum - 1)).Take(pageSize).ToList();  
  286.         }  
  287.         /// <summary>  
  288.         /// 获取指定条件的实体集合  
  289.   
  290.         /// </summary>  
  291.         /// <typeparam name="T">泛型类型参数</typeparam>  
  292.         /// <param name="query">查询条件</param>  
  293.         /// <returns></returns>  
  294.         public virtual List<T> GetAllEntity<T>(Expression<Func<T, bool>> query) where T : class  
  295.         {  
  296.             var table = GetTable<T>();  
  297.             return (from t in table  
  298.                     select t).Where(query).ToList();  
  299.         }  
  300.   
  301.         /// <summary>  
  302.         /// 获取指定条件的实体集合  
  303.   
  304.         /// </summary>  
  305.         /// <typeparam name="T">泛型类型参数</typeparam>  
  306.         /// <param name="query">查询条件</param>        
  307.         /// <param name="orderAsc"></param>         
  308.         /// <returns></returns>  
  309.         public virtual List<T> GetAllEntity<T>(Expression<Func<T, bool>> query, bool isAsc, Func<T, object> order) where T : class  
  310.         {  
  311.             var table = GetTable<T>();  
  312.             if (isAsc)  
  313.                 return (from t in table  
  314.                         select t).Where(query).OrderBy(order).ToList();  
  315.             return (from t in table  
  316.                     select t).Where(query).OrderByDescending(order).ToList();  
  317.         }  
  318.   
  319.         public virtual List<T> GetAllEntity<T>() where T : class  
  320.         {  
  321.             var table = GetTable<T>();  
  322.             return (from t in table  
  323.                     select t).ToList();  
  324.         }  
  325.         #endregion  
  326.  
  327.  
  328.         #region 新增实体  
  329.         /// <summary>  
  330.         /// 新增单个实体  
  331.         /// </summary>  
  332.         /// <typeparam name="T">泛型类型参数</typeparam>  
  333.         /// <param name="entity">待插入的实体</param>  
  334.         /// <returns></returns>  
  335.         public virtual void InsertEntity<T>(T entity) where T : class  
  336.         {  
  337.             var table = GetTable<T>();  
  338.             table.AddObject(entity);  
  339.             entities.SaveChanges();  
  340.         }  
  341.         /// <summary>  
  342.         /// 批量新增实体  
  343.         /// </summary>  
  344.         /// <typeparam name="T">泛型类型参数</typeparam>  
  345.         /// <param name="entityList">待添加的实体集合</param>  
  346.         /// <returns></returns>  
  347.         public virtual void BatchInsertEntity<T>(List<T> entityList) where T : class  
  348.         {  
  349.             if (entityList.Count > 0)  
  350.             {  
  351.                 var table = GetTable<T>();  
  352.                 foreach (var item in entityList)  
  353.                 {  
  354.                     table.AddObject(item);//DeleteAllOnSubmit(toDeletedColl);  
  355.                 }  
  356.                 entities.SaveChanges();  
  357.             }  
  358.         }  
  359.         #endregion  
  360.  
  361.         #region 删除实体  
  362.         /// <summary>  
  363.         /// 根据条件删除指定实体  
  364.         /// </summary>  
  365.         /// <typeparam name="T">实体</typeparam>  
  366.         /// <param name="query">条件</param>  
  367.         /// <returns>bool</returns>  
  368.         public virtual void DeleteEntitys<T>(Expression<Func<T, bool>> query) where T : class  
  369.         {  
  370.             var table = GetTable<T>();  
  371.             var toDeletedColl = table.Where(query);  
  372.             if (toDeletedColl != null && toDeletedColl.Count() > 0)  
  373.             {  
  374.                 foreach (var item in toDeletedColl)  
  375.                 {  
  376.                     table.DeleteObject(item);//DeleteAllOnSubmit(toDeletedColl);  
  377.                 }  
  378.                 entities.SaveChanges();  
  379.             }  
  380.         }  
  381.         #endregion  
  382.     }  
  383. }  

http://blog.csdn.net/jacky4955/article/details/25411975

posted @ 2014-12-30 14:52  关中秦人  阅读(149)  评论(0编辑  收藏  举报