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
    }
}
时间: 2024-12-28 16:38:02

Entity Framework底层操作封装V2版本号(2)的相关文章

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

由于同志们一直给我提建议说.曾经发的版本号有问题.所以经过了我这一年多的使用和扩展,如今方法基本稳定了. 如今贴出来给大家使用: 首先上场的是数据库操作层: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Linq.Expressions; using System.Data.Objects.DataClasses; using System.Re

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

因为同志们一直给我提建议说,以前发的版本有问题.所以经过了我这一年多的使用和扩展,现在方法基本稳定了.现在贴出来给大家使用: 首先上场的是数据库操作层: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Linq.Expressions; using System.Data.Objects.DataClasses; using System.Refl

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.Refl

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

现在是附加的,组合查询需要的扩展类.大家知道lanmda表达式的组合条件比较麻烦,所以就加了一样一个类,方便进行组合查询: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Linq.Expressions; namespace JFrame.AccessCommon { public static class PredicateExtensions

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

这个版本里面,因为涉及到了多库的操作,原有的系统方法不能做到这样的事情了.所以这里有了一点区别 这个类的主要用作就是,连接字符串的作用,默认是指向默认配置里面的,但是你可以指向其他的连接 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Configuration; namespace JFrame.Dal { public class DataBa

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

这个框架到现在最大的变化马上就要出现了,哪就是对缓存的使用.因为系统经常要去读取数据库数据,但是大家知道,数据库的处理能力是有限的,所以对于一些数据量不大,但是又 需要经常去读取的功能来说,更好的方法就是使用缓存. 上面4的方法是不适用缓存的 using System; using System.Collections.Generic; using System.Linq; using System.Text; using JFrame.AccessCommon; using System.Da

.NET Entity Framework入门操作

Entity Framework是微软借鉴ORM思想开发自己的一个ORM框架. ORM就是将数据库表与实体对象(相当于三层中的Model类)相互映射的一种思想. 最大的优点就是非常方便的跨数据库平台.因为该技术不需要知道用的是什么数据库,这也是.net中Linq能To任何对象的原因. 这门技术为什么可以跨平台呢?是因为它只需要修改一下config文件就可以了,只要指定连接字符串,驱动程序,就可以根据不同数据库生成不同的Sql语句,当你的项目用户用到不同的数据库时,就不需要像修改SQL语句了. E

Entity Framework 基础操作(1)

EF是微软推出的官方ORM框架,默认防注入可以配合LINQ一起使用,更方便开发人员. 首先通过SQLSERVER现在有的数据库类生产EF 右键->添加->新建项,选择AOD.NET实体数据模型,来自数据库的Code FIrst 完成添加后会生成多个文件,并且在你的项目的配置文件中有数据库的链接字符串,下面文件中 “name=Test”, Test就是连接字符串的name public partial class TestDB : DbContext { public TestDB() : ba

entity framework 时间操作

//比较天数 //当天用户 var useractiveentity = db.UserActive.Where(u => u.UserInfoID == uid && System.Data.Objects.EntityFunctions.DiffDays(DateTime.Now, u.Createtime) == 0).FirstOrDefault(); if (useractiveentity == null) { UserActive userActive = new Us