先对dbcontext进行扩展

public static class DBContextExtention
    {
        /// <summary>
        /// 仅更新对象的指定属性,调用后仍然需要调用db.SaveChanges()
        /// </summary>
        /// <typeparam name="T">实体</typeparam>
        /// <param name="context">上下文</param>
        /// <param name="model">要修改的实体对象</param>
        /// <param name="value">指定实体对象要修改的字段和值,通过匿名对象传递</param>
        public static void Modify<T>(this DbContext context, T model, object value)
            where T : class
        {
            context.Update(model);

            //4.1将 对象 添加到 EF中
            var entry = context.Entry<T>(model);

            //4.2先设置 对象的包装 状态为 Unchanged
            entry.State = EntityState.Unchanged;

            var dic = value.ToDictionary();
            //4.3循环 被修改的属性名 数组
            foreach (var kv in dic)
            {
                var v = entry.Property(kv.Key);
                if (v != null)
                {
                    //4.4将每个 被修改的属性的状态 设置为已修改状态;后面生成update语句时,就只为已修改的属性 更新
                    v.IsModified = true;
                    v.CurrentValue = kv.Value;
                }
            }
        }

        static Dictionary<string, object?> ToDictionary(this object obj)
        {
            if (obj == null)
                return [];

            var dictionary = new Dictionary<string, object?>();
            foreach (var property in obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
            {
                if (property.CanRead)
                {
                    dictionary[property.Name] = property.GetValue(obj, null);
                }
            }
            return dictionary;
        }

    }

使用示例:

            if (!client.IsOnline)
            {
                device.State = DeviceState.Offline;
            }
            //db.Device.Update(device);
            db.Modify(device, new { device.State });
            db.SaveChanges();

 

 posted on 2024-06-05 17:16  Lucien.Bao  阅读(6)  评论(0编辑  收藏  举报