Entity Framework中实现指定字段更新

时间:2021-03-26 14:53:09
            foreach (var entity in databasePatents)
            {
                var patentTmp = sourcePClist.FirstOrDefault(p => p.Oid == entity.Oid);
                if (patentTmp != null)
                {
                    var sourceProperties = patentTmp.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
                    var targetProperties = entity.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
                   var modifiedFileds = new List<string>();
                    foreach (PropertyInfo item in sourceProperties)
                    {
                        if (item.Name == "Id" || item.Name == "LegalUpdateTime" || item.Name == "Oid"|| item.Name == "CreateDate")
                            continue;
                        if (item.PropertyType.IsValueType || item.PropertyType.Name.StartsWith("String"))
                        {
                            if (item.GetValue(patentTmp) != null)
                            {
                                modifiedFileds.Add(item.Name);
                                var firstOrDefault = targetProperties.FirstOrDefault(p => p.Name == item.Name);
                                if (firstOrDefault != null)
                                    firstOrDefault.SetValue(entity, item.GetValue(patentTmp));
                            }
                        }

                    }
                    ObjectSet.Attach(entity);
                    if (modifiedFileds.Any())
                    {
                        var stateEntry = ((IObjectContextAdapter)Context).ObjectContext.ObjectStateManager.GetObjectStateEntry(entity);
                        foreach (string filed in modifiedFileds)
                        {
                            stateEntry.SetModifiedProperty(filed);
                        }
                    }
                    else
                    {
                        Context.Entry(entity).State = EntityState.Modified;
                    }
                }

            }