首页 > 技术文章 > Entity Framework底层操作封装(2)

dingdingmao 2013-06-20 16:48 原文

http://blog.csdn.net/jacky4955/article/details/9138411(http://blog.csdn.net/jacky4955/article/details/9138411)里面,是对操作底层的封装,但对于偶来说,其实并不满意。因为操作还是显得太过繁琐,每一次都得去实现基础的几个方法,即使他的代码很少,这个也是一种浪费,作为一个攻城师,坚决不做码农,不去重复同样的工作。于是针对DAL的数据操作做了一个父类。

上代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using System.Data.Objects.DataClasses;
using System.Reflection;
namespace NOAS.PublicOpinionMonitor.Access.Common
{
    public class AccessBase<T> where T : class
    {
        private string _strTableName;
        private string _ColumsName;
        private string _PrimaryKey;
        private Type _PrimaryKeyType;

        public AccessBase(string PrimaryKey = "", string strTableName = "", string ColumsName = "")
        {
            Type t = typeof(T);
            if (string.IsNullOrEmpty(strTableName))
            {
                strTableName = t.Name; //GetType(t).ToString();
            }
            _strTableName = strTableName;
            if (string.IsNullOrEmpty(ColumsName))
            {
                _ColumsName = " * ";
            }

            if (string.IsNullOrEmpty(PrimaryKey))
            {
                PropertyInfo[] infos = t.GetProperties();
                _PrimaryKey = getPrimaryKey(infos);
            }
        }





        /// <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)
                {
                    _PrimaryKeyType = propertyInfo.PropertyType;
                    return columnName = propertyInfo.Name;
                }
            }
            return columnName;

        }


        /// <summary>
        /// 执行数据库操作基础类方法
        /// </summary>
        protected DataCommon Data = new DataCommon();

        /// <summary>
        /// 增加单个实体
        /// </summary>
        /// <param name="t"></param>
        public virtual void addEntity(T t)
        {
            Data.InsertEntity<T>(t);
        }

        public virtual T getSingleEntity(Expression<Func<T, bool>> query)
        {
            return Data.GetSingleEntity<T>(query);
        }


        public virtual T getSingleEntity(object PrimaryKeyId)
        {
            StringBuilder strWhere = new StringBuilder();
            switch (_PrimaryKeyType.Name.ToLower())
            {
                case "int16":
                case "int32":
                case "int64":
                case "int":
                case "decimal":
                case "double":
                case "float":
                case "short":
                    strWhere.AppendFormat(" {0}={1}", _PrimaryKey, PrimaryKeyId);
                    break;
                case "bool":
                case "boolean":
                    if ((bool)PrimaryKeyId)
                    { strWhere.AppendFormat(" {0}=1", _PrimaryKey);}
                    else 
                    { strWhere.AppendFormat(" {0}=0", _PrimaryKey); }

                    break;
                default:
                    strWhere.AppendFormat(" {0}='{1}'", _PrimaryKey, PrimaryKeyId);
                    break;
            }

            return getListByWhere(strWhere.ToString()).FirstOrDefault();
        }

        /// <summary>
        /// 修改单个实体
        /// </summary>
        /// <param name="t"></param>
        public virtual void updateEntity(T t)
        {
            Data.Update<T>(t);
        }


        /// <summary>
        /// 根据条件删除信息
        /// </summary>
        /// <param name="query">条件</param>
        public virtual void deleteEntity(Expression<Func<T, bool>> query)
        {
            Data.DeleteEntitys<T>(query);
        }


        /// <summary>
        /// 根据条件获取相关监测信息表
        /// </summary>
        /// <param name="strWhere">Where条件</param>
        /// <returns>数据集合</returns>
        protected virtual List<T> getListByWhere(string strWhere)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.AppendFormat("select {1} from {0}", _strTableName, _ColumsName);
            if (!string.IsNullOrEmpty(strWhere))
            {
                strSql.AppendFormat(" where {0}", strWhere);
            }
            return Data.ExecuteQuery<T>(strSql.ToString()).ToList();
        }

        /// <summary>
        /// 获取最大主键
        /// </summary>
        /// <returns></returns>
        protected virtual int? getMaxPrimaryKey()
        {
            StringBuilder strSql = new StringBuilder();
            strSql.AppendFormat("select max({1}) from {0}", _strTableName, _PrimaryKey);
            return Data.ExecuteQuery<int>(strSql.ToString()).FirstOrDefault();
        }
    }
}

这样继承的子类,就自动拥有了增删改查的基础方法。

推荐阅读