EF只更新变化的字段

摘要

在使用EF的时候,由于表字段较多,所以在更新的时候,想要只更新变化的字段,有没有办法呢?

解决办法

代码片段

复制代码
     public async Task<int> UpdateAsync(T entity, List<string> fieldNames)
        {
            using (var context = new RetailContext())
            {

                if (fieldNames != null && fieldNames.Count > 0)
                {
                    context.Set<T>().Attach(entity);
                    foreach (var item in fieldNames)
                    {
                        context.Entry<T>(entity).Property(item).IsModified = true;
                    }
                }
                else
                {
                    context.Entry<T>(entity).State = System.Data.Entity.EntityState.Modified;
                }

                return await context.SaveChangesAsync();
            }
        }
复制代码

将变化的字段名称放在集合中,并修改其是否变化的状态。

复制代码
        public async Task<int> UpdateAsync(T entity, Dictionary<string, object> dic)
        {
            try
            {
              
                if (dic != null)
                {
                    SetValue<T>(dic, entity);
                    return await _baseData.UpdateAsync(entity, dic.Keys.ToList());
                }
                else
                {
                    return await _baseData.UpdateAsync(entity, null);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
复制代码
复制代码
    /// <summary>
        /// 通过反射设置值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dic"></param>
        /// <param name="entity"></param>
        public static void SetValue<T>(Dictionary<string, object> dic, T entity) where T : class ,new()
        {
            Type t = entity.GetType();
            PropertyInfo[] properties = t.GetProperties();
            foreach (var item in properties)
            {
                foreach (var key in dic.Keys)
                {
                    if (key.ToLower() == item.Name.ToLower())
                    {
                        switch (item.PropertyType.ToString())
                        {
                            case "System.Int32":
                                item.SetValue(entity, Convert.ToInt32(dic[key]), null);
                                break;
                            case "System.Boolean":
                                item.SetValue(entity, Convert.ToBoolean(dic[key]), null);
                                break;
                            case "System.String":
                                item.SetValue(entity, Convert.ToString(dic[key]), null);
                                break;
                            case "System.Decimal":
                                item.SetValue(entity, Convert.ToDecimal(dic[key]), null);
                                break;
                            case "System.DateTime":
                                item.SetValue(entity, Convert.ToDateTime(dic[key]), null);
                                break;
                            case "System.Guid":
                                Guid g = dic[key] == null ? new Guid() : new Guid(dic[key].ToString());
                                item.SetValue(entity, g, null);                                
                                break;
                            default:
                                item.SetValue(entity, dic[key], null);
                                break;
                        }

                    }
                }
            }
        }
复制代码

通过反射的方式对变化的字段进行赋值。字段中保存变化的字段名称与值。

posted @   wolfy  阅读(5114)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
历史上的今天:
2015-08-09 [Asp.net]缓存简介
2014-08-09 [Asp.net MVC]Asp.net MVC5系列——实现编辑、删除与明细信息视图
点击右上角即可分享
微信分享提示