Example #1
0
        /// <summary>
        /// 4.x扩展修改方法(把不须要修改的列用LAMBDA数组表示出来)
        /// </summary>
        /// <param name="model">要修改的实体对象</param>
        /// <param name="ignoreProperties">不须要修改的相关字段</param>
        /// <returns>受影响的行数</returns>
        public int UpdateEntity(T model, params Expression <Func <T, object> >[] ignoreProperties)
        {
            int iret = -1;

            //Logger("修改" + typeof(T).Name + "中的数据", () =>
            //{
            using (DbContext db = new Model.Entities()) //DBContextFactory().GetDbContext()
            {
                db.Entry <T>(model).State = EntityState.Detached;
                db.Set <T>().Attach(model);

                DbEntityEntry entry = db.Entry <T>(model);
                entry.State = System.Data.EntityState.Unchanged;

                Type t = typeof(T);
                List <PropertyInfo> proInfos = t.GetProperties(BindingFlags.Instance | BindingFlags.Public).ToList();

                Dictionary <string, PropertyInfo> dicPros = new Dictionary <string, PropertyInfo>();
                proInfos.ForEach(
                    p => dicPros.Add(p.Name, p)
                    );

                if (ignoreProperties != null)
                {
                    foreach (var ignorePropertyExpression in ignoreProperties)
                    {
                        //根据表达式得到对应的字段信息
                        var ignorePropertyName = new PropertyExpressionParser <T>(ignorePropertyExpression).Name;
                        dicPros.Remove(ignorePropertyName);
                    }
                }

                foreach (string proName in dicPros.Keys)
                {
                    entry.Property(proName).IsModified = true;
                }
                iret = db.SaveChanges();
            }
            return(iret);
        }
Example #2
0
        /// <summary>
        /// 修改实
        /// </summary>
        /// <param name="entity">修改对象</param>
        /// <param name="pNas">要修改的属性名称集体</param>
        /// <returns></returns>
        public int UpdateEntity(T entity, params string[] pNas)
        {
            try
            {
                using (DbContext _dbx = new Model.Entities())
                {
                    _dbx.Entry <T>(entity).State = EntityState.Detached;//oracle数据库没这一句不能修改

                    DbEntityEntry upEntity = _dbx.Entry <T>(entity);
                    upEntity.State = System.Data.EntityState.Unchanged;
                    foreach (string pNa in pNas)
                    {
                        upEntity.Property(pNa).IsModified = true;
                    }
                    return(_dbx.SaveChanges());
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }