zoukankan      html  css  js  c++  java
  • EF部分字段更新,自动忽略null字段

     某个项目里的update代码是类似这样的

            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;
            }

     当运行的时候EF在UPDATE的时候会自动更新所有字段,这样就会增加不少麻烦

     例如我们在页面里编辑数据保存的时候只希望更新提交的数据,没有POST的字段希望保持不变,例如createtime(创建时间),hit(点击数量)等。

     于是我想到在UPDATE的时候遍历entity对象的所有属性,不是null的属性标记为Modified=true,这样在SaveChanges的时候只会更新非NULL的字段了。大致代码如下:

            public T Update<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;
            }

    这样处理后目前运行良好,如果有更好的办法请告诉我。

  • 相关阅读:
    http
    jquery
    wsgi
    urls控制器
    模板template
    ORM
    C++中获取汉字拼音首字缩写/全拼及生僻字的处理
    C语言函数strstr
    CString 成员函数用法
    判断字符串中是否存在中文
  • 原文地址:https://www.cnblogs.com/relax/p/4965008.html
Copyright © 2011-2022 走看看