EF 部分更新 忽略NULL
//全部更新 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; }
//部分更新,propNames为需要更新的字段 public void Update(T entity, string[] propNames) { var oldEntity = _masterContext.Attach(entity);//告诉EF entity,因为调用DbContext.Attach方法后,EF Core会将entity实体的State值(可以通过testDBContext.Entry(person).State查看到)更改回EntityState.Unchanged foreach (var prop in propNames) { oldEntity.Property(prop).IsModified = true; } _masterContext.SaveChanges(); }