利用反射更新类

利用反射更新类

      #region 利用反射更新类
        /// <summary>
        /// 利用反射更新类
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        /// <param name="db"></param>
        public static void UpdateModel<T>(T entity, DbContext db) where T : class
        {
            db.Set<T>().Attach(entity);
            foreach (System.Reflection.PropertyInfo p in entity.GetType().GetProperties())
            {
                //if (p.GetValue(entity) != null&&p.GetValue(entity).ToString()!= "&nbsp;")
                if (p.GetValue(entity) != null)
                {
                    db.Entry(entity).Property(p.Name).IsModified = true;
                }
            }
            db.SaveChanges();
        }
        #endregion

 

posted @ 2017-04-20 09:27  代码沉思者  阅读(172)  评论(0编辑  收藏  举报