make Entity Framework revert empty strings to null!

 public override int SaveChanges(SaveOptions options)
        {
            foreach (EntityObject entity in this.ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Modified).Select(entry => entry.Entity))
            {
                //if (entity == null || entity is User) continue;

                string str = typeof(string).Name;

                var props = entity.GetType().GetProperties();

                var properties = from p in entity.GetType().GetProperties()
                                 where
                                 p.PropertyType.Name == str &&
                                 p.IsDefined(typeof(EdmScalarPropertyAttribute), false) &&
                                 p.IsDefined(typeof(DataMemberAttribute), false)
                                 select p;

                foreach (var item in properties)
                {
                    string value = (string)item.GetValue(entity, null);
                    if (value != null && value.Trim().Length == 0)
                        entity.GetType().GetField("_" + item.Name, System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance).SetValue(entity, null);
                }
            }
            return base.SaveChanges(options);
        }
posted @ 2011-12-09 10:43  阿新  阅读(343)  评论(0编辑  收藏  举报