Is there an option to make Entity Framework revert empty strings to null?

后端 未结 8 922
时光说笑
时光说笑 2021-02-06 09:30

I am using an ADO.NET Entity-Framework ObjectContext to access my data store.

I want the if values are set with empty strings, they should automatically become null.

8条回答
  •  灰色年华
    2021-02-06 09:58

    Just for completeness, here is the accepted answer written as a partial class instead of inherited. Note that this version also trims strings.

    using System.Data;
    using System.Data.Objects;
    using System.Linq; 
    public partial class MyObjectContext {
        private const string StringType = "String";
        private const EntityState SavingState = EntityState.Added | EntityState.Modified;
    
        public override int SaveChanges(SaveOptions options) {
            var savingEntries = this.ObjectStateManager.GetObjectStateEntries(SavingState);
    
            foreach (var entry in savingEntries) {
                var curValues = entry.CurrentValues;
                var fieldMetadata = curValues.DataRecordInfo.FieldMetadata;
                var stringFields = fieldMetadata.Where(f => f.FieldType.TypeUsage
                                                             .EdmType.Name == StringType);
    
                foreach (var stringField in stringFields) {
                    var ordinal = stringField.Ordinal;
                    var curValue = curValues[ordinal] as string;
    
                    if (curValue != null && curValue.All(char.IsWhiteSpace)) {
                        curValues.SetValue(ordinal, null);
                    }
                    else if (curValue != null && curValue != curValue.Trim()) {
                        curValues.SetValue(ordinal, curValue.Trim());
                    }
                }
            }
            return base.SaveChanges(options);
        }
    }
    

    I have also shown the required usings because I find it frustrating when I copy'n'paste code and the IDE throws up some errors about type or namespace not found.

提交回复
热议问题