方便单个实体更新的DbContext扩展方法,比如Edit页面

        /// <summary>
        /// 将实体内非null字段标记为已更新,将在调用db.SaveChanges();后一起更新
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="db"></param>
        /// <param name="entity"></param>
        public static void Update<T>(this DbContext db, T entity) where T : class, new()
        {
            if (entity == null)
                throw new ArgumentException("The database entity can not be null.");

            DbEntityEntry<T> entry = db.Entry<T>(entity);
            entry.State = System.Data.EntityState.Unchanged;
            Type entityType = entity.GetType();
            var table = entityType.GetProperties();
            foreach (var change in table)
            {
                if (change.GetValue(entity, null) != null)//&& change.Name != "ID"
                {
                    entry.Property(change.Name).IsModified = true;
                }
            }
        }

 就是这样。。 可以不需要Find下来再保存上去了。 多个实体一起保存也是可以的,不支持联表同时更新实体。

后来发现把字符攒清空后绑定会变成null导致无法更新,请参考:

http://www.cnblogs.com/LoveJerryZhang/archive/2013/05/08/3067376.html

---

PS:话说如果要单条语句批量更新的话,可以用Entity Framework Extended里的update方法

原文地址:https://www.cnblogs.com/gxrsprite/p/3054719.html