Entity Framework 第五篇 状态跟踪

本人建议尽量使用EntityState来表名Entry的状态,而不要使用Configuration.AutoDetectChangesEnabled自动状态跟踪,为什么我这么建议呢?他们到底有什么异同?

  public int Update<TEntity>(Expression<Func<TEntity, bool>> predicate, Action<TEntity> updateAction) where TEntity : class
        {
            if (predicate == null)
                throw new ArgumentNullException("predicate");
            if (updateAction == null)
                throw new ArgumentNullException("updateAction");

            //dbContext.Configuration.AutoDetectChangesEnabled = true;
            var _model = dbContext.Set<TEntity>().Where(predicate).ToList();
            if (_model == null) return 0;
            _model.ForEach(p =>
            {
                updateAction(p);
                dbContext.Entry<TEntity>(p).State = EntityState.Modified;
            });
            return Save();
        }

上面是一个Update操作

通过 dbContext.Entry<TEntity>(p).State = EntityState.Modified;来更改状态最后提交

但是如果我们采用自动跟踪状态,写法如下

 public int Update<TEntity>(Expression<Func<TEntity, bool>> predicate, Action<TEntity> updateAction) where TEntity : class
        {
            if (predicate == null)
                throw new ArgumentNullException("predicate");
            if (updateAction == null)
                throw new ArgumentNullException("updateAction");

            dbContext.Configuration.AutoDetectChangesEnabled = true;
            var _model = dbContext.Set<TEntity>().Where(predicate).ToList();
            if (_model == null) return 0;
            _model.ForEach(p =>
            {
                updateAction(p);
            });
            return Save();
        }

那么他们最后到底会有什么异同呢?如果采用后者,如果实体的字段值并没有变化,最后提交的时候,受影响数为0,也就是数据上下文,发现该实体没有任何变化,不做数据库操作,但是如果采用EntityState.Modified,实体字段无论有没有发生变化都会做数据库操作,所以受影响的行数不为0

原文地址:https://www.cnblogs.com/njcxwz/p/5581446.html