• 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();
    }
  • 相关阅读:
    redis安装
    redis的使用场景和基本数据类型
    (传输层)tcp协议
    async/await
    Promise对象
    对称加密与非对称加密
    Js遍历数组总结
    HTTPS加密传输过程
    HTML节点操作
    Js的new运算符
  • 原文地址:https://www.cnblogs.com/myfqm/p/13935767.html
Copyright © 2020-2023  润新知