一般的更新代码是这样的

public T Update<T>(T entity) where T : ModelBase
        {
            var set = this.Set<T>();
            set.Attach(entity);
            this.Entry<T>(entity).State = EntityState.Modified;
            this.SaveChanges();
            return entity;
        }

 

但是有时候有更新的时候,如果为null则不更新这字段,这个时候就会有问题了,这个时候用另一个方法。。

public T Update2<T>(T entity) where T : ModelBase
        {
            var set = this.Set<T>();
            set.Attach(entity);
            foreach (System.Reflection.PropertyInfo p in entity.GetType().GetProperties())
            {
                if (p.GetValue(entity) != null)
                {
                    this.Entry<T>(entity).Property(p.Name).IsModified = true;
                }
            }
            this.SaveChanges();
            return entity;
        }

  

 

相关文章:

  • 2022-12-23
  • 2021-12-19
  • 2021-12-01
  • 2022-12-23
  • 2019-09-24
  • 2021-08-30
  • 2021-06-22
  • 2021-07-22
猜你喜欢
  • 2022-12-23
  • 2021-11-28
  • 2021-08-22
  • 2022-12-23
  • 2021-10-17
  • 2022-12-23
相关资源
相似解决方案