当前位置: 移动技术网 > IT编程>开发语言>.net > BIM工程信息管理系统-EF实体框架数据操作基类

BIM工程信息管理系统-EF实体框架数据操作基类

2019年08月02日  | 移动技术网IT编程  | 我要评论

贝丝-汉弗莱斯,兔友美图,上网时长查询

ef实体框架数据操作基类主要是规范增、改、查、分页、lambda表达式条件处理,以及异步操作等特性,这样能够尽可能的符合基类这个特殊类的定义,实现功能接口的最大化重用和统一。

1、程序代码

 /// <summary>
    /// mssql数据库 数据层的父类
    /// </summary>
    /// <typeparam name="t"></typeparam>
    public class basedal<t> where t : class
    {
        //ef上下文
        private readonly dbcontext _db;
      #region 00 单例模式

        private static basedal<t> _minstance = null;
        private static object obj = new object();

        public basedal(dbcontext db)
        {
            _db = db;
        }

        public static basedal<t> managercontent(dbcontext dbcontext)
        {
            if (_minstance == null)
            {
                lock (obj)
                {
                    _minstance = new basedal<t>(dbcontext);
                }
            }
            return _minstance;
        }

        #endregion
 #region 1.0 新增 实体 +int add(t model)
        /// <summary>
        /// 新增 实体
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool add(t model)
        {
            try
            {
                _db.set<t>().add(model);
                _db.savechanges();
                //保存成功后,会将自增的id设置给 model的 主键属性,并返回受影响行数
            }
            catch (entityexception ex)
            {
                loghelper.error("add", ex);
                loghelper.error(ex.message); throw ex.innerexception;
            }
            catch (dbexception exc)
            {
                loghelper.error("add", exc);
                throw exc.innerexception;
            } 
            return true;
        }
        #endregion
 #region 2.0 根据 id 删除 +bool del(t model)
        /// <summary>
        /// 根据 id 删除
        /// </summary>
        /// <param name="model">包含要删除id的对象</param>
        /// <returns></returns>
        public bool del(t model)
        {
            try
            {
                _db.set<t>().attach(model);
                _db.set<t>().remove(model);
               _db.savechanges();
            }
            catch (entityexception ex)
            {
                loghelper.error("add", ex);
                loghelper.error(ex.message); throw ex.innerexception;
            }
            catch (dbexception exc)
            {
                loghelper.error("add", exc);
                throw exc.innerexception;
            } 
            return true;
        }
        #endregion
      #region 3.0 根据条件删除 +bool delby(expression<func<t, bool>> delwhere)
        /// <summary>
        /// 3.0 根据条件删除
        /// </summary>
        /// <param name="delwhere"></param>
        /// <returns></returns>
        public bool delby(expression<func<t, bool>> delwhere)
        {
            try
            {
                //3.1查询要删除的数据
                list<t> listdeleting = _db.set<t>().where(delwhere).tolist();
                //3.2将要删除的数据 用删除方法添加到 ef 容器中
                listdeleting.foreach(u =>
                {
                    _db.set<t>().attach(u);//先附加到 ef容器
                    _db.set<t>().remove(u);//标识为 删除 状态
                });
                //3.3一次性 生成sql语句到数据库执行删除
                 _db.savechanges();
            }
            catch (entityexception ex)
            {
                loghelper.error("add", ex);
                loghelper.error(ex.message); throw ex.innerexception;
            }
            catch (dbexception exc)
            {
                loghelper.error("add", exc);
                throw exc.innerexception;
            } 
            return true;
        }
        #endregion
  #region 4.0 修改 +bool modify(t model, params string[] pronames)
        /// <summary>
        /// 4.0 修改,如:
        /// t u = new t() { uid = 1, uloginname = "asdfasdf" };
        /// this.modify(u, "uloginname");
        /// </summary>
        /// <param name="model">要修改的实体对象</param>
        /// <param name="pronames">要修改的 属性 名称</param>
        /// <returns></returns>
        public bool modify(t model, params string[] pronames)
        {
            try
            {
                //4.1将 对象 添加到 ef中
                dbentityentry entry = _db.entry<t>(model);
                //4.2先设置 对象的包装 状态为 unchanged
                entry.state = entitystate.unchanged;
                //4.3循环 被修改的属性名 数组
                foreach (string proname in pronames)
                {
                    //4.4将每个 被修改的属性的状态 设置为已修改状态;后面生成update语句时,就只为已修改的属性 更新
                    entry.property(proname).ismodified = true;
                }
                //4.4一次性 生成sql语句到数据库执行
                _db.savechanges();
            }
            catch (entityexception ex)
            {
                loghelper.error("add", ex);
                loghelper.error(ex.message); throw ex.innerexception;
            }
            catch (dbexception exc)
            {
                loghelper.error("add", exc);
                throw exc.innerexception;
            } 

            return true;
        }
        #endregion
  #region 4.1 批量修改 +bool modify(t model, expression<func<t, bool>> wherelambda, params string[] modifiedpronames)
        /// <summary>
        /// 4.0 批量修改
        /// </summary>
        /// <param name="model">要修改的实体对象</param>
        /// <param name="wherelambda">查询条件</param>
        /// <param name="modifiedpronames">要修改的 属性 名称</param>
        /// <returns></returns>
        public bool modifyby(t model, expression<func<t, bool>> wherelambda, params string[] modifiedpronames)
        {
            try
            {
                //4.1查询要修改的数据
                list<t> listmodifing = _db.set<t>().where(wherelambda).tolist();

                //获取 实体类 类型对象
                type t = typeof(t); // model.gettype();
                //获取 实体类 所有的 公有属性
                list<propertyinfo> proinfos = t.getproperties(bindingflags.instance | bindingflags.public).tolist();
                //创建 实体属性 字典集合
                dictionary<string, propertyinfo> dictpros = new dictionary<string, propertyinfo>();
                //将 实体属性 中要修改的属性名 添加到 字典集合中 键:属性名  值:属性对象
                proinfos.foreach(p =>
                {
                    if (modifiedpronames.contains(p.name))
                    {
                        dictpros.add(p.name, p);
                    }
                });

                //4.3循环 要修改的属性名
                foreach (string proname in modifiedpronames)
                {
                    //判断 要修改的属性名是否在 实体类的属性集合中存在
                    if (dictpros.containskey(proname))
                    {
                        //如果存在,则取出要修改的 属性对象
                        propertyinfo proinfo = dictpros[proname];
                        //取出 要修改的值
                        object newvalue = proinfo.getvalue(model, null); //object newvalue = model.uname;

                        //4.4批量设置 要修改 对象的 属性
                        foreach (t usro in listmodifing)
                        {
                            //为 要修改的对象 的 要修改的属性 设置新的值
                            proinfo.setvalue(usro, newvalue, null); //usro.uname = newvalue;
                        }
                    }
                }
                //4.4一次性 生成sql语句到数据库执行
                 _db.savechanges();
            }
            catch (entityexception ex)
            {
                loghelper.error("add", ex);
                loghelper.error(ex.message); throw ex.innerexception;
            }
            catch (dbexception exc)
            {
                loghelper.error("add", exc);
                throw exc.innerexception;
            } 

            return true;
        }
        #endregion
   #region 4.2 修改个单个实体
        public bool modify(t model)
        {
            try
            {
                _db.entry(typeof (t)).state = entitystate.modified;
                //4.4一次性 生成sql语句到数据库执行
                _db.savechanges();
            }
            catch (entityexception ex)
            {
                loghelper.error("add", ex);
                loghelper.error(ex.message); throw ex.innerexception;
            }
            catch (dbexception exc)
            {
                loghelper.error("add", exc);
                throw exc.innerexception;
            }

            return true;
        }
        #endregion
#region 5.0 根据条件查询 +iqueryable<t> getlistby(expression<func<t,bool>> wherelambda)
        /// <summary>
        /// 5.0 根据条件查询 +list<t> getlistby(expression<func<t,bool>> wherelambda)
        /// </summary>
        /// <param name="wherelambda">lambda表达式</param>
        /// <returns></returns>
        public iqueryable<t> getlistby(expression<func<t, bool>> wherelambda)
        {
            try
            {
                return _db.set<t>().where(wherelambda);
            }
            catch (entityexception ex)
            {
                loghelper.error("add", ex);
                loghelper.error(ex.message); throw ex.innerexception;
            }
            catch (dbexception exc)
            {
                loghelper.error("add", exc);
                throw exc.innerexception;
            } 
        }
        #endregion
#region 5.1 根据条件 排序 和查询 + iqueryable<t> getlistby<tkey>
        /// <summary>
        /// 5.1 根据条件 排序 和查询
        /// </summary>
        /// <typeparam name="tkey">排序字段类型</typeparam>
        /// <param name="wherelambda">查询条件 lambda表达式</param>
        /// <param name="orderlambda">排序条件 lambda表达式</param>
        /// <returns></returns>
        public iqueryable<t> getlistby<tkey>(expression<func<t, bool>> wherelambda, expression<func<t, tkey>> orderlambda)
        {
            try
            {
                return _db.set<t>().where(wherelambda).orderby(orderlambda);
            }
            catch (entityexception ex)
            {
                loghelper.error("add", ex);
                loghelper.error(ex.message); throw ex.innerexception;
            }
            catch (dbexception exc)
            {
                loghelper.error("add", exc);
                throw exc.innerexception;
            } 
        }
        #endregion
#region 5.2 根据条件查询 返回单条数据 t getentity(expression<func<t, bool>> wherelambda)

        public t getentity(expression<func<t, bool>> wherelambda)
        {
            try
            {
                return _db.set<t>().first(wherelambda);
            }
            catch (entityexception ex)
            {
                loghelper.error("add", ex);
                loghelper.error(ex.message); throw ex.innerexception;
            }
            catch (dbexception exc)
            {
                loghelper.error("add", exc);
             throw   exc.innerexception;
            }  
        }
        #endregion
    #region 6.0 分页查询 + iqueryable<t> getpagedlist<tkey>
        /// <summary>
        /// 6.0 分页查询 + iqueryable<t> getpagedlist<tkey>
        /// </summary>
        /// <param name="pageindex">页码</param>
        /// <param name="pagesize">页容量</param>
        /// <param name="wherelambda">条件 lambda表达式</param>
        /// <param name="orderby">排序 lambda表达式</param>
        /// <returns></returns>
        public iqueryable<t> getpagedlist<tkey>(int pageindex, int pagesize, expression<func<t, bool>> wherelambda, expression<func<t, tkey>> orderby)
        {
            // 分页 一定注意: skip 之前一定要 orderby
            try
            {
                return _db.set<t>().where(wherelambda).orderby(orderby).skip((pageindex - 1) * pagesize).take(pagesize);
            }
            catch (entityexception ex)
            {
                loghelper.error("add", ex);
                loghelper.error(ex.message); throw ex.innerexception;
            }
            catch (dbexception exc)
            {
                loghelper.error("add", exc);
                throw exc.innerexception;
            } 
        }
        #endregion
#region 7.0执行sql+string execmaxvaluesql()
        public string execmaxvaluesql()
        {
            string sql = @"begin tran
                declare @value bigint
                update " + typeof(t).name + @"
                set value = value+1;
                select @value = value from " + typeof(t).name + @";
                 select cast(@value as varchar(10));
                commit tran";
            string value = _db.database.sqlquery<string>(sql).first();

            return value;
        }
        #endregion
   }

2、 日志记录组件采用 log4net

   public class loghelper
    {
        private static readonly log4net.ilog log = log4net.logmanager.getlogger("applicationlog");
        public static void info(string info)
        {
            log.info(info);
        }
        public static void info(string info, exception ex)
        {
            log.info(info, ex);
        }
        public static void error(string info, exception ex)
        {
            log.info(info, ex);
        }
        public static void error(string info)
        {
            log.error(info);
        }
        public void debug(string info)
        {
            log.debug(info);
        }
        public void debug(string info, exception se)
        {
            log.debug(info, se);
        }
        public void warn(string info)
        {
            log.warn(info);
        }
        public void warn(string info, exception ex)
        {
            log.warn(info, ex);
        }
        public void fatal(string info)
        {
            log.fatal(info);
        }
        public void fatal(string info, exception ex)
        {
            log.fatal(info, ex);
        }
    }
<?xml version="1.0" encoding="utf-8" ?>
<log4net>
  <logger name="applicationlog">
    <level value="info" />
    <appender-ref ref="rollingfile" />
  </logger>

  <appender name="rollingfile" type="log4net.appender.rollingfileappender, log4net" >
    <param name="file" value="servicelog.txt" />
    <param name="appendtofile" value="true" />
    <param name="rollingstyle" value="date" />
    <param name="maximumfilesize" value="5mb"></param>
    <param name="datepattern" value="_yyyy.mm.dd" />
    <param name="staticlogfilename" value="true" />
    <layout type="log4net.layout.patternlayout, log4net">
      <param name="conversionpattern" value="%d - %m%n" />
    </layout>
  </appender>
</log4net>

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网